问题描述:
最近开发遇到个问题,就是UIButton响应了UIContolEventTouchDragEnter、UIControlEventTouchDragExit事件后,在拖出按钮的时候不会立即响应事件,而是真正超出70px的才会响应。
猜测苹果这样做的原因是估计到小按钮手指点击容易有抖动,会不小心有移出按钮的误操作。
效果是这样的:(盗个图)
解决办法:
响应UIContolEventTouchDragInside、UIControlEventTouchDragOutSide方法(大家会问和enter、exit的区别)
UIControlEventTouchDragInside 当一次触摸在控件窗口内拖动时。 UIControlEventTouchDragOutside 当一次触摸在控件窗口之外拖动时。 UIControlEventTouchDragEnter 当一次触摸从控件窗口之外拖动到内部时。 UIControlEventTouchDragExit 当一次触摸从控件窗口内部拖动到外部时。
响应到一个函数里:
[btn addTarget:self action:@selector(sendButtonDrag:withEvent:) forControlEvents:UIControlEventTouchDragInside]; [btn addTarget:self action:@selector(sendButtonDrag:withEvent:) forControlEvents:UIControlEventTouchDragOutside];
- (IBAction)sendButtonDrag:(UIButton *)sender withEvent:(UIEvent *)event { if ([self isInButtonBounds:sender event:event]) { // 在里面 } else { // 在外面 } } - (BOOL)isInButtonBounds:(UIButton *)button event:(UIEvent *)event { UITouch *touch = [[event allTouches] anyObject]; CGFloat boundsExtension = 5.0f; //扩展范围阀值 CGRect outerBounds = CGRectInset(button.bounds, -1 * boundsExtension, -1 * boundsExtension); BOOL touchOutside = !CGRectContainsPoint(outerBounds, [touch locationInView:button]); if (touchOutside) { BOOL previewTouchInside = CGRectContainsPoint(outerBounds, [touch previousLocationInView:button]); if (previewTouchInside) { // UIControlEventTouchDragExit } else { // UIControlEventTouchDragOutside } return NO; } else { BOOL previewTouchOutside = !CGRectContainsPoint(outerBounds, [touch previousLocationInView:button]); if (previewTouchOutside) { // UIControlEventTouchDragEnter } else { // UIControlEventTouchDragInside } return YES; } }
当然也要在 UIControlEventTouchUpInside的响应函数里做上面判断,不然的话会显示离开,但是抬手还是会响应点击函数的。
- (IBAction)sendAudioRecordButton:(id)sender withEvent:(UIEvent *)event { if ([self isInButtonBounds:sender event:event]) { // 点击按钮 } }
时间: 2024-11-08 22:36:52