[TOC]
问题描述
最近在做语音输入按钮时,利用UIButton来处理。当手指拖拽出button边界时,UIControlEventTouchDragExit并未立即触发,继续托拽出距离button边界大约70像素时才触发。
代码实现
- (void)setVoiceBtnEvent {
[_voiceBtn addTarget:self action:@selector(btnTouchUp:withEvent:) forControlEvents:UIControlEventTouchUpInside];
[_voiceBtn addTarget:self action:@selector(btnTouchUp:withEvent:) forControlEvents:UIControlEventTouchUpOutside];
[_voiceBtn addTarget:self action:@selector(btnDragged:withEvent:) forControlEvents:UIControlEventTouchDragInside];
[_voiceBtn addTarget:self action:@selector(btnDragged:withEvent:) forControlEvents:UIControlEventTouchDragOutside];
}
// touch up
- (void)btnTouchUp:(UIButton *)sender withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGFloat boundsExtension = 10.0f;// 触发边界暂时设置为10
CGRect outerBounds = CGRectInset(sender.bounds, -1 * boundsExtension, -1 * boundsExtension);
BOOL touchOutside = !CGRectContainsPoint(outerBounds, [touch locationInView:sender]);
if (touchOutside) {
// UIControlEventTouchUpOutside
} else {
// UIControlEventTouchUpInside
}
}
// drag
- (void)btnDragged:(UIButton *)sender withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGFloat boundsExtension = 10.0f;// 触发边界暂时设置为10
CGRect outerBounds = CGRectInset(sender.bounds, -1 * boundsExtension, -1 * boundsExtension);
BOOL touchOutside = !CGRectContainsPoint(outerBounds, [touch locationInView:sender]);
if (touchOutside) {
BOOL previewTouchInside = CGRectContainsPoint(outerBounds, [touch previousLocationInView:sender]);
if (previewTouchInside) {
// UIControlEventTouchDragExit
} else {
// UIControlEventTouchDragOutside
}
} else {
BOOL previewTouchOutside = !CGRectContainsPoint(outerBounds, [touch previousLocationInView:sender]);
if (previewTouchOutside) {
// UIControlEventTouchDragEnter
} else {
// UIControlEventTouchDragInside
}
}
}
网友评论