iPhone SDK:Trouble Dragging a UIImageView

2019-04-08 15:00发布

I am trying to drag a UIImageView around the iphone screen in my app.

Currently The drag functionality I have set up is fine and dragging the image does move it around the screen, the trouble is that you don't have to drag the image view to move it, you can also drag anywhere on the screen and it will move the image. I am new to this platform so I can't really think about what to do to solve this issue. My current code to drag the image is:

 - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    CGPoint pt = [[touches anyObject] locationInView:pig];
    startLocation = pt;


}
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
    CGPoint pt = [[touches anyObject] locationInView:pig];
    CGRect frame = [pig frame];
    frame.origin.x += pt.x - startLocation.x;
    frame.origin.y += pt.y - startLocation.y;
    [pig setFrame: frame];
}

Any help appreciated. By the way pig is the UIImageView. Also I have noticed that if I set the user interaction of the Image View "pig" to enabled the image is no longer drag able,but when it isn't set to enabled It is.

3条回答
放我归山
2楼-- · 2019-04-08 15:33

You can try to subclass UIImageView and implement touchesBegan: and touchesMoved: on it directly. Then in InterfaceBuilder select your subclass for the UIImageView.

alt text http://img.skitch.com/20090728-xetretcfubtcj7ujh1yc8165wj.jpg

Oh yes, now you will need to set the user interaction again...

查看更多
Evening l夕情丶
3楼-- · 2019-04-08 15:40

You need to enclose it in begin / commit Animation sequences at least in your timer thread:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.02]  /* 0.02 seconds suration*/

/* move pig coordinates here */

[UIView commitAnimations];

Save the new movement in touchesMoved and then process them in the timer thread.

查看更多
女痞
4楼-- · 2019-04-08 15:53

You can use an UIView category to make it draggable and define the draggable area: https://github.com/rtoshiro/TXDragAndDrop

查看更多
登录 后发表回答