本文介绍了奇怪的 UIButton 行为:这正常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 UIButton,想要在用户触摸它时做某事,但随后将手指移到按钮外并未触摸屏幕.所以看来我需要监听 UIControlEventTouchUpOutside 事件.

I have a simple UIButton and want to do something when the user touches it, but then moves the finger outside the button and untouches the screen. So that seems like I need to listen for the UIControlEventTouchUpOutside event.

在我的视图控制器中,我这样做了:

In my view controller, I did this:

UIButton *bt = [[UIButton alloc] initWithFrame:rect];
[bt setBackgroundColor:[UIColor whiteColor]];
[bt addTarget:self action:@selector(onTouchUpOutside) forControlEvents:UIControlEventTouchUpOutside];
[self.view addSubview:bt];

以及对应的动作方法:

- (void)onTouchUpOutside {
    NSLog(@"touchUpOutside");
}

现在猜猜是什么?我触摸按钮,然后将手指拖到按钮外面,取消触摸屏幕并且没有记录任何消息.事实上,它会记录我发生了 UIControlEventTouchUpInside 事件,即使我的手指并没有真正位于按钮上方.似乎我可以在触摸时将手指围绕该按钮移动大约 150% 的宽度和高度,当我不触摸时它会告诉我手指在按钮中.但是当我把它移得很远(=足够远)时,我确实收到了touchUpOutside"日志消息.那么这只是苹果的另一个疯狂,比如延迟 -touchesMoved 和类似的东西吗?还是我做错了什么?

now guess what? I touch the button, then drag the finger outside of it, untouch the screen and no message is logged. Indeed it would log me that an UIControlEventTouchUpInside event has happened, even if my finger is not really above the button. It seems like I can move the finger about 150% of the width and hight around that button while touching, and it will tell me that the finger was in the button when I untouch. But when I move it very far away (= far away enough), I do get that "touchUpOutside" log message. So is that just another madness from apple, like the delay in -touchesMoved and stuff like that? Or did I do something wrong?

推荐答案

touchUpInside 会在您将手指移到按钮外一点时触发,因为人们的手指很大且不精确.

touchUpInside is fired when you move your finger a bit outside the button, because people have big, imprecise fingers.

如果您真的想覆盖此行为,请在 touchUpInside 处理程序中检查触摸的位置,然后如果在按钮之外触摸它,则直接调用 touchUpOutside 处理程序界限.

If you really want to override this behaviour, in a touchUpInside handler check the location of the touch, then call the touchUpOutside handler directly if the touch it outside the button's bounds.

这篇关于奇怪的 UIButton 行为:这正常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 08:46