美文网首页iCoder
UIButton事件的边界问题

UIButton事件的边界问题

作者: 大斌小姜 | 来源:发表于2016-08-08 19:04 被阅读37次

    [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
    
            }
        }
    }
    
    

    相关文章

      网友评论

        本文标题:UIButton事件的边界问题

        本文链接:https://www.haomeiwen.com/subject/amursttx.html