您可以将computed property
添加到您的扩展,你可以在你的控制器设置,如果你想使灾区是这样的:
fileprivate let minimumHitArea = CGSize(width: 100, height: 100)
extension UIButton {
var isIncreasedHitAreaEnabled: Bool {
get {
// default value is false, so you can easily handle from outside when to enable the increased hit area of your specific button
return false
}
set {
}
}
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// if the button is hidden/disabled/transparent it can't be hit
if self.isHidden || !self.isUserInteractionEnabled || self.alpha < 0.01 { return nil }
// only if it's true the hit area can be increased
if isIncreasedHitAreaEnabled {
// increase the hit frame to be at least as big as `minimumHitArea`
let buttonSize = self.bounds.size
let widthToAdd = max(minimumHitArea.width - buttonSize.width, 0)
let heightToAdd = max(minimumHitArea.height - buttonSize.height, 0)
let largerFrame = self.bounds.insetBy(dx: -widthToAdd/2, dy: -heightToAdd/2)
// perform hit test on larger frame
return (largerFrame.contains(point)) ? self : nil
}
return self
}
}
然后在您的视图控制器只需设置isIncreasedHitAreaEnabled
到true
如果你要增加它的特定按钮(例如,在您的viewDidLoad
):
override func viewDidLoad() {
super.viewDidLoad()
specialButton.isIncreasedHitAreaEnabled = true
}
更新:
首先您使用的方法不能像预期的那样工作。而且我的方法与computed property
没有像我想象的那样工作。所以即使这种方法不能像预期的那样工作,我只想用computed property
来更新我的方法。 因此,要从外部设置属性,您可以使用Associated Objects。也看看here。有了这个解决方案,现在有可能从你的控制器处理Bool
财产isIncreasedHitAreaEnabled
:
fileprivate let minimumHitArea = CGSize(width: 100, height: 100)
private var xoAssociationKey: UInt8 = 0
extension UIButton {
var isIncreasedHitAreaEnabled: Bool {
get {
return (objc_getAssociatedObject(self, &xoAssociationKey) != nil)
}
set(newValue) {
objc_setAssociatedObject(self, &xoAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// if the button is hidden/disabled/transparent it can't be hit
if self.isHidden || !self.isUserInteractionEnabled || self.alpha < 0.01 { return nil }
if isIncreasedHitAreaEnabled {
// increase the hit frame to be at least as big as `minimumHitArea`
let buttonSize = self.bounds.size
let widthToAdd = max(minimumHitArea.width - buttonSize.width, 0)
let heightToAdd = max(minimumHitArea.height - buttonSize.height, 0)
let largerFrame = self.bounds.insetBy(dx: -widthToAdd/2, dy: -heightToAdd/2)
// perform hit test on larger frame
return (largerFrame.contains(point)) ? self : nil
}
return self
}
}
的替代方法@ ronatory的答案是:(1)亚类的UIButton为,比如说,'SpecialButton',然后延伸,代替的UIButton。 – dfd
请注意,从扩展中重写函数是一个坏主意,并且不允许在纯“swift”中,只能在Objective-C NSObject类中使用。引用Apple Swift iBook:“扩展可以向某种类型添加新功能,但它们无法覆盖现有功能”。摘自:Apple Inc.“Swift Programming Language(Swift 3.0.1)。”iBooks。 https://itun.es/us/jEUH0.l –
更新了我的答案。但不幸的是,该方法不能像预期的那样工作。我认为你应该尝试马特的答案http://stackoverflow.com/a/42182054/5327882 – ronatory