我有一个36x36的UIButton,我想添加填充(实质上就像CSS),以便可触摸区域为the recommended 44x44。
我已尝试通过Interface Builder添加边缘插入以及下面的代码,但我尝试过的任何内容都不会增加可触摸区域。
contentEdgeInsets
边缘插入是否仅适用于包含文本的按钮?
更新
我已尝试设置imageEdgeInsets
,titleEdgeInsets
和{{1}}无效。
我可以通过编辑实际图像并增加图标周围的边框来扩展可触摸区域。 (这不是首选方式,但如果我找不到另一种解决方案,我可能会走这条路。)
答案 0 :(得分:1)
我在Swift this回答中覆盖了它的确有效:
import UIKit
import ObjectiveC
private var KEY_HIT_TEST_EDGE_INSETS: String = "HitTestEdgeInsets"
extension UIButton {
public func setHitTestEdgeInsets(inout hitTestEdgeInsets: UIEdgeInsets) {
let value = NSValue(&hitTestEdgeInsets, withObjCType:NSValue(UIEdgeInsets: UIEdgeInsetsZero).objCType)
objc_setAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
private func hitTestEdgeInsets() -> UIEdgeInsets {
let value = objc_getAssociatedObject(self, &KEY_HIT_TEST_EDGE_INSETS)
if (value != nil) {
var edgeInsets: UIEdgeInsets = UIEdgeInsetsZero
value.getValue(&edgeInsets)
return edgeInsets
} else {
return UIEdgeInsetsZero
}
}
override public func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
if UIEdgeInsetsEqualToEdgeInsets(self.hitTestEdgeInsets(), UIEdgeInsetsZero) || !self.enabled || self.hidden {
return super.pointInside(point, withEvent: event)
}
let relativeFrame = self.bounds
let hitFrame = UIEdgeInsetsInsetRect(relativeFrame, self.hitTestEdgeInsets());
return CGRectContainsPoint(hitFrame, point)
}
}
使用:
var insets: UIEdgeInsets = UIEdgeInsetsMake(-20, -20, -20, -20)
button.setHitTestEdgeInsets(&insets)