首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TouchesMoved与UITouch

TouchesMoved与UITouch
EN

Stack Overflow用户
提问于 2013-12-02 21:14:21
回答 2查看 848关注 0票数 0

我正在创建一个简单的应用程序,您可以通过触摸和拖动UIImageView来移动它。

我的UIImageView叫做imv

代码语言:javascript
复制
-(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语句,它就无效了。我能做什么?

谢谢你的回答

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-12-02 21:49:58

除非您已经子类UIImageView (不太可能),否则您的视图将接收触摸事件。

如今,将UIGestureRecognizer用于这类事情变得更简单&更常见,在本例中是UIPanGestureRecognizer

例如:

代码语言:javascript
复制
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);
    }
}
票数 1
EN

Stack Overflow用户

发布于 2013-12-02 21:49:35

从一些实验来看,[touch view]似乎返回的是主UIView,而不是您的子视图,因此if语句不工作的问题(我在故事板xib中添加了UIImageView )。编辑--这是因为UIImageView在默认情况下不处理触摸事件--参见这里。当在UIView中添加一个常规的viewDidLoad时,似乎就像您预期的那样起作用了。

无论如何,这个经过修改的代码版本适合我。

代码语言:javascript
复制
-(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];
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20337964

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档