UIButton擴大響應區域

  • UIButton的響應區域應當不小于44x44pt

方法一

  • 繼承UIButton,覆寫Button的方法
  • 代碼如下:
- (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,覆寫Button的方法
  • 代碼如下:
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
    CGRect bounds = self.bounds;
    //若原熱區小于44x44,則放大熱區,否則保持原大小不變
    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都被擴大的方法,而且不經過自己調用就實現不太好
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

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