MY_ iOS 按鈕超過父檢視範圍無法響應事件的處理方法

weixin_34249678發表於2017-03-19
3372511-6767ad4ab5bbb179.png
Paste_Image.png

當按鈕超過了父檢視範圍,點選是沒有反應的。因為訊息的傳遞是從最下層的父檢視開始呼叫hittest方法。


- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {  
    UIView *view = [super hitTest:point withEvent:event];  
    return view;  
}  

當存在view時才會傳遞對應的event,現在點選了父檢視以外的範圍,自然返回的是nil。所以當子檢視(比如按鈕btn)因為一些原因超出了父檢視範圍,就要重寫hittest方法,讓其返回對應的子檢視,來接收事件。

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {  
    UIView *view = [super hitTest:point withEvent:event];  
    if (view == nil) {  
    CGPoint tempoint = [btn convertPoint:point fromView:self];  
        if (CGRectContainsPoint(btn.bounds, tempoint))   
    {  
           view = btn;  
        }  
     }             
    return view;  
}  

超越點選事件

//
//  UIButton+TapScope.m
//  SuningSummer
//
//  Created by snping on 14-8-15.
//  Copyright (c) 2014年 Suning. All rights reserved.
//

#import "UIButton+TapScope.h"
#import <objc/runtime.h>

static void * kHitEdgeInsetsKey = &kHitEdgeInsetsKey;

@implementation UIButton (TapScope)

- (void)setHitEdgeInsets:(UIEdgeInsets)hitEdgeInsets
{
    NSValue *value = [NSValue valueWithUIEdgeInsets:hitEdgeInsets];
    objc_setAssociatedObject(self, kHitEdgeInsetsKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIEdgeInsets)hitEdgeInsets
{
    NSValue * value = objc_getAssociatedObject(self, kHitEdgeInsetsKey);
    if(value) {
        return [value UIEdgeInsetsValue];
    }
    
    return UIEdgeInsetsZero;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    if (UIEdgeInsetsEqualToEdgeInsets(self.hitEdgeInsets, UIEdgeInsetsZero) || !self.enabled || self.hidden) {
        return [super pointInside:point withEvent:event];
    }
    
    CGRect hitFrame = UIEdgeInsetsInsetRect(self.bounds, self.hitEdgeInsets);
    
    return CGRectContainsPoint(hitFrame, point);
}

相關文章