你怎么知道touchesBegan中被触摸的对象?

时间:2010-04-15 19:53:51

标签: ios iphone uiimageview uitouch touchesbegan

我知道这是一个非常常见的问题,但每个网站上的所有答案都不起作用!如果您仍然不知道我的意思,那么这行代码可能会帮助您理解。


- (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, and more optionsbutton时,它不会执行任何操作,顺便提一下UIImageViews。我也尝试使用isEqual:代替==,但这也没有成功。有什么建议吗?

2 个答案:

答案 0 :(得分:35)

您必须为所有UIImageView设置userinteractionEnabled = YES,否则他们将不会收到触摸事件。同时更改行:

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

 UITouch *touch = [touches anyObject];

答案 1 :(得分: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];
    }
}