×
您的位置: 首页 > 编程笔记

你怎么知道touchesBegan中被触摸的对象?(How do you tell what object is being touched in touchesBegan?)

Android 时间:2020-06-15  查看:697   收藏

I know that this is a very commonly asked question, but all of the answers on every website don't work!  If you still don't know what I mean, then maybe this line of code will help you understand.

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

It doesn't do anything when you touch nextbutton, prevbutton, and more optionsbutton, which are UIImageViews by the way. I have also tried using isEqual: instead of ==, but that hasn't worked out either.  Any suggestions?

解决方案

You have to set userinteractionEnabled = YES for all your UIImageViews otherwise they will not receive touch events. Also change the line:

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

to

 UITouch *touch = [touches anyObject];

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



  
 - (void)touchesBegan:(NSSet *)触及withEvent:(UIEvent *)事件{
 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和更多选项按钮,顺便说一句是 UIImageViews 。我也尝试使用 isEqual:而不是 == ,但这也没有成功。有什么建议?


解决方案

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



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





  UITouch * touch = [触及anyObject];


 

0% (0)
0% (0)