2010-04-15 65 views
15

我知道這是一個非常常見的問題,但是每個網站上的所有答案都不起作用!如果你仍然不知道我的意思,那麼也許這行代碼將幫助你理解。如何判斷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:而不是==,但是這還沒有解決。有什麼建議麼?

回答

34

您必須爲所有UIImageViews設置userinteractionEnabled = YES,否則它們將不會接收觸摸事件。也改變了線路:

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

UITouch *touch = [touches anyObject]; 
+1

謝謝你的userinteractionEnabled = YES提示。我猛敲頭,想知道爲什麼我的UIImageView沒有註冊觸摸。 – DenVog 2012-12-14 18:18:34

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]; 
    } 
}