大家好,今天小編將會帶大家了解一下UIButton在frame不變的情況下,如何改變有效點擊區(qū)域(也就是我們所說的改變熱區(qū))。
先睹為快,讓我們看一下demo效果圖:

-
Demo解讀
- 1.上邊的較大灰色按鈕
topGrayReduceClickAreaContainerButton,
在其上放置了一個可以穿透事件的黃色子視圖yellowTopRealClickAreaView,
改變了topGrayReduceClickAreaContainerButton的有效點擊區(qū)域為yellowTopRealClickAreaView范圍。 - 2.下邊的較大灰色視圖 是一個
_bottomGrayContainerLabel,
在其上放置了一個可以接收交互的blueRealEffectiveClickAreaLabel,
在blueRealEffectiveClickAreaLabel上放置了一個很小的紅色按鈕redEnlargeClickAreaButton,改變了redEnlargeClickAreaButton的有效點擊區(qū)域為blueRealEffectiveClickAreaLabel范圍。
- 1.上邊的較大灰色按鈕
應(yīng)用場景
有時設(shè)計師給的某些可點擊的控件的尺寸較小。
按照設(shè)計師給的圖做出相應(yīng)的視覺效果比較容易。
但可能出現(xiàn)一些問題:由于Button過小,不太容易點擊到有效區(qū)域,所以用戶雖然在感官上點擊了控件,卻并沒有得到反饋。
- 官方:
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. - 解釋:為了便于用戶點擊控件后有反應(yīng),需要設(shè)置足夠大小的交互控件,給可點擊控件的大約44 x 44 點的點擊區(qū)域
解決方案
通過重寫- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;
以改變按鈕的有效點擊區(qū)域
關(guān)鍵代碼
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;
// 若熱區(qū)小于 44 * 44 則放大熱區(qū) 否則保持原大小不變
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
參考學(xué)習(xí)地址
了解更多iOS及相關(guān)新技術(shù),請關(guān)注我們的公眾號:

關(guān)注我們的途徑有:
QiShare(簡書)
QiShare(掘金)
QiShare(知乎)
QiShare(GitHub)
QiShare(CocoaChina)
QiShare(StackOverflow)
QiShare(微信公眾號)
推薦文章:
iOS UIButton之UIControlEvents介紹
奇舞周刊第 271 期:寫給設(shè)計師的機器學(xué)習(xí)指南