技术开发 频道

新手必读:iPhone SDK示例代码解析

  可以拖动的对象items

  下面展示如何简单的创建一个可以拖动的image对象:

  1. 创建一个新的类来继承UIImageView。

@interface myDraggableImage : UIImageView {
}

 

  2. 在新的类实现的时候添加两个方法:

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    
    
// Retrieve the touch point
    CGPoint pt
= [[touches anyObject] locationInView:self];
    startLocation
= pt;
    [[self superview] bringSubviewToFront:self];
    
}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
    
    
// Move relative to the original touch point
    CGPoint pt
= [[touches anyObject] locationInView:self];
    CGRect frame
= [self frame];
    frame.origin.x
+= pt.x - startLocation.x;
    frame.origin.y
+= pt.y - startLocation.y;
    [self setFrame:frame];
}

  3. 现在再创建一个新的image加到我们刚创建的UIImageView里面,就可以展示了。

dragger = [[myDraggableImage alloc] initWithFrame:myDragRect];
[dragger setImage:[UIImage imageNamed:@
"myImage.png"]];
[dragger setUserInteractionEnabled:YES];
0
相关文章