swift 代码实现:新建一个UIButtonAddSelectedArea.swift文件
import UIKit
extension UIButton {
// 重写 point(inside:with:) 方法来增加点击区域
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
var bounds = self.bounds
// 如果按钮尺寸小于 44*44 ,则扩展点击区域,否则保持原大小
let widthDelta = max(44.0-bounds.size.width, 0)
let heightDelta = max(44.0-bounds.size.height, 0)
bounds = bounds.insetBy(dx: -0.5*widthDelta, dy: -0.5*heightDelta)
return bounds.contains(point)
}
}
oc代码实现: 给uibutton扩展一个分类,然后在pch文件中引用这个分类
UIButton+addSelectedArea.h文件
#import <UIKit/UIKit.h>
@interface UIButton (addSelectedArea)
@end
UIButton+addSelectedArea.m文件
#import "UIButton+addSelectedArea.h"
@implementation UIButton (addSelectedArea)
- (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);
}
@end