我正在创建一个简单的应用程序,您可以通过触摸和拖动UIImageView来移动它。
我的UIImageView叫做imv
-(void ) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch * touch = [touches anyObject];
if([touch view] == self.imv){
CGPoint location = [touch locationInView:self.view];
self.imv.center = location;
}
}
-(void ) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch * touch = [touches anyObject];
if([touch view] == self.imv){
CGPoint location = [touch locationInView:self.view];
self.imv.center = location;
}
}我整天都在试着解决这个问题,我不知道是怎么回事。如果我禁用If语句,它就无效了。我能做什么?
谢谢你的回答
发布于 2013-12-02 21:49:58
除非您已经子类UIImageView (不太可能),否则您的视图将接收触摸事件。
如今,将UIGestureRecognizer用于这类事情变得更简单&更常见,在本例中是UIPanGestureRecognizer。
例如:
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(dragImageView:)];
[self.imv addGestureRecognizer:pan];
- (void)dragImageView:(UIPanGestureRecognizer *)dragImageView {
if(UIGestureRecognizerStateBegan == state) {
originalCenter = self.imv.center; // add CGPoint originalCenter; member
} else if(UIGestureRecognizerStateChanged == state) {
CGPoint translate = [pan translationInView:self.imv.superview];
self.imv.center = CGPointMake(originalCenter.x + translate.x, originalCenter.y + translate.y);
}
}发布于 2013-12-02 21:49:35
从一些实验来看,[touch view]似乎返回的是主UIView,而不是您的子视图,因此if语句不工作的问题(我在故事板xib中添加了UIImageView )。编辑--这是因为UIImageView在默认情况下不处理触摸事件--参见这里。当在UIView中添加一个常规的viewDidLoad时,似乎就像您预期的那样起作用了。
无论如何,这个经过修改的代码版本适合我。
-(void)moveImageForTouches:(NSSet*)touches
{
UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInView:self.view];
if(CGRectContainsPoint(self.imv.frame, location))
{
self.imv.center = location;
}
}
-(void ) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[self moveImageForTouches:touches];
}
-(void ) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self moveImageForTouches:touches];
}https://stackoverflow.com/questions/20337964
复制相似问题