touchesBegan中如何确定被触摸的对象?

16

我知道这是一个非常常见的问题,但是所有网站上的答案都不起作用!如果你还不明白我的意思,那么也许这行代码会帮助你理解。


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:self.view];
    if (touch.view == nextbutton)
        [self performSelector:@selector(next)];
    if (touch.view == prevbutton)
        [self performSelector:@selector(previous)];
    if (touch.view == moreoptionsbutton)
        [self performSelector:@selector(moresettings)];
}

当您触摸 nextbutton,prevbutton 和 more optionsbutton 时,它们(顺便说一下)是 UIImageViews 的时候,它什么也不做。我还尝试使用 isEqual: 而不是 ==,但这也没有奏效。有什么建议吗?

2个回答

35

你需要为所有的UIImageView设置userInteractionEnabled = YES,否则它们将无法接收触摸事件。同时更改以下代码:

 UITouch *touch = [[event allTouches] anyObject];
to
 UITouch *touch = [touches anyObject];

1
谢谢您提供的userinteractionEnabled = YES提示。我一直在苦思冥想为什么我的UIImageView无法注册触摸事件。 - DenVog

2
我创建了一个检查,以确保在继续之前点击的是我期望的视图。
if( [touch.view isKindOfClass:[Custom class]] ){
    CGPoint touchPoint = [touch locationInView:self.view];

    if( CGRectContainsPoint( self.customClassOne.frame, touchPoint )
       || CGRectContainsPoint( self.customClassTwo.frame, touchPoint ) ){
        [self touchOnCustomClass];
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接