UIButton擴大響應(yīng)區(qū)域

  • UIButton的響應(yīng)區(qū)域應(yīng)當(dāng)不小于44x44pt

方法一

  • 繼承UIButton,覆寫B(tài)utton的方法
  • 代碼如下:
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (!self.userInteractionEnabled || self.isHidden || self.alpha <= 0.01) {
        return nil;
    }
    CGRect touchuRect = CGRectInset(self.bounds, -44 , -44);
    if (CGRectContainsPoint(touchuRect, point)) {
        for (UIView *subView in [self.subviews reverseObjectEnumerator]) {
            CGPoint convertedPoint = [subView convertPoint:point toView:self];
            UIView *hinTestView = [subView hitTest:convertedPoint withEvent:event];
            if (hinTestView) {
                return hinTestView;
            }
        }
        return self;
    }
    return nil;
}

方法二

  • 也是繼承UIButton,覆寫B(tài)utton的方法
  • 代碼如下:
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
    CGRect bounds = self.bounds;
    //若原熱區(qū)小于44x44,則放大熱區(qū),否則保持原大小不變
    CGFloat widthDelta = MAX(44.0 - bounds.size.width, 0);
    CGFloat heightDelta = MAX(44.0 - bounds.size.height, 0);
    bounds = CGRectInset(bounds, -0.5 * widthDelta, -0.5 * heightDelta);
    return CGRectContainsPoint(bounds, point);
}

點擊測試,代碼如下:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    
    // 方法一的按鈕
    LXKButton *redButton = [[LXKButton alloc] initWithFrame:CGRectMake(100, 100, 2, 2)];
    redButton.backgroundColor = [UIColor redColor];
    [redButton addTarget:self action:@selector(redButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:redButton];
    
    // 方法二的按鈕
    LXKButton2 *blackButton = [[LXKButton2 alloc] initWithFrame:CGRectMake(100, 300, 2, 2)];
    blackButton.backgroundColor = [UIColor blackColor];
    [blackButton addTarget:self action:@selector(blackButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:blackButton];
}

- (void)redButtonClicked {

    NSLog(@"點擊紅色按鈕");
}

- (void)blackButtonClicked {
    
    NSLog(@"點擊黑色按鈕");
}

  • 寫成category好嗎?感覺都所有的button都被擴大的方法,而且不經(jīng)過自己調(diào)用就實現(xiàn)不太好
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 問題 在開發(fā)過程中經(jīng)常會遇到設(shè)計給出的button尺寸偏小的情況.這種UIButton在使用中會非常難點擊,極大降...
    走進科學(xué)閱讀 2,579評論 0 4
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,085評論 4 61
  • 第1章 熟悉Objective-C 第1條 了解Objective-C語言的起源 Objective-C是一種“消...
    __silhouette閱讀 751評論 0 4
  • *面試心聲:其實這些題本人都沒怎么背,但是在上海 兩周半 面了大約10家 收到差不多3個offer,總結(jié)起來就是把...
    Dove_iOS閱讀 27,585評論 30 472
  • 去年飄雪迎歸客,今朝春風(fēng)送別情。 相離難舍無言悅,只是風(fēng)寒目相凝。 對面我送君淚盈,轉(zhuǎn)身君送我背影。 前方路遙多坎...
    折美閱讀 1,074評論 0 0

友情鏈接更多精彩內(nèi)容