iOS UIButton之改变有效点击区域(改变热区)

级别:★☆☆☆☆
标签:「UIButton」「热区」
作者: WYW
审校: Xs·H

大家好,今天小编将会带大家了解一下UIButtonframe不变的情况下,如何改变有效点击区域(也就是我们所说的改变热区)。

先睹为快,让我们看一下demo效果图:

《iOS UIButton之改变有效点击区域(改变热区)》

  • Demo解读
    • 1.上边的较大灰色按钮topGrayReduceClickAreaContainerButton
      在其上放置了一个可以穿透事件的黄色子视图yellowTopRealClickAreaView
      改变了topGrayReduceClickAreaContainerButton的有效点击区域为yellowTopRealClickAreaView范围。
    • 2.下边的较大灰色视图 是一个_bottomGrayContainerLabel
      在其上放置了一个可以接收交互的blueRealEffectiveClickAreaLabel
      blueRealEffectiveClickAreaLabel上放置了一个很小的红色按钮redEnlargeClickAreaButton,改变了redEnlargeClickAreaButton的有效点击区域为blueRealEffectiveClickAreaLabel范围。

应用场景

有时设计师给的某些可点击的控件的尺寸较小
按照设计师给的图做出相应的视觉效果比较容易。
但可能出现一些问题:由于Button过小,不太容易点击到有效区域,所以用户虽然在感官上点击了控件,却并没有得到反馈。

  • 官方: Make it easy for people to interact with content and controls by giving each interactive element ample spacing. Give tappable controls a hit target of about 44 x 44 points.
  • 解释:为了便于用户点击控件后有反应,需要设置足够大小的交互控件,给可点击控件的大约44 x 44 点的点击区域

解决方案

通过重写- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;
以改变按钮的有效点击区域

关键代码

QiChangeClickEffectiveAreaButton.h:

#import <UIKit/UIKit.h>

@interface QiChangeClickEffectiveAreaButton : UIButton

//! 点击范围的缩小值 此值目前只是为了演示 把较大按钮的点击范围变小
@property (nonatomic,assign) CGFloat qi_clickAreaReduceValue;

@end

QiChangeClickEffectiveAreaButton.m:

#import "QiChangeClickEffectiveAreaButton.h"

@implementation QiChangeClickEffectiveAreaButton

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    
    if (_qi_clickAreaReduceValue > 0) {
        if (_qi_clickAreaReduceValue >= CGRectGetWidth(self.bounds) / 2) {
            _qi_clickAreaReduceValue = CGRectGetWidth(self.bounds) / 2;
        }
        
        CGRect bounds = CGRectInset(self.bounds, _qi_clickAreaReduceValue, _qi_clickAreaReduceValue);
        return CGRectContainsPoint(bounds, point);
    }
    
    // 获取bounds 实际大小
    CGRect bounds = self.bounds;
    
    // 若热区小于 44 * 44 则放大热区 否则保持原大小不变
    CGFloat widthDelta = MAX(44.0 - bounds.size.width, .0);
    CGFloat heightDelta = MAX(44.0 - bounds.size.height, .0);
    // 扩大bounds
    bounds = CGRectInset(bounds, -0.5 * widthDelta, -0.5 * heightDelta);
    // 点击的点在新的bounds 中 就会返回YES
    return CGRectContainsPoint(bounds, point);
}

@end

代码GitHub地址

参考学习地址

关注我们的途径有:
QiShare(简书)
QiShare(掘金)
QiShare(知乎)
QiShare(GitHub)
QiShare(CocoaChina)
QiShare(StackOverflow)
QiShare(微信公众号)

推荐文章:
iOS UIButton之UIControlEvents介绍
奇舞周刊第 271 期:写给设计师的机器学习指南

    原文作者:QiShare
    原文地址: https://www.jianshu.com/p/4cb97a0c0fc9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞