【发布时间】:2017-02-11 21:39:57
【问题描述】:
在我的应用程序中,我有一个很小的UIButton,所以我考虑增加它的命中区域。
我找到了一个扩展:
fileprivate let minimumHitArea = CGSize(width: 100, height: 100)
extension UIButton {
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 }
// 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
}
}
但是当我使用它时,我的应用程序中的每个按钮都有更大的点击区域。我想将它增加到只有一个specialButton - 我该怎么做?
【问题讨论】:
-
@ronatory 的答案的替代方法是 (1) 将 UIButton 子类化为
SpecialButton,然后扩展它而不是 UIButton。 -
请注意,从扩展中覆盖函数是一个坏主意,并且不允许在“纯”swift中,仅在Objective-C NSObject类中。引用 Apple Swift iBook 的话:“扩展可以为类型添加新功能,但不能覆盖现有功能”摘自:Apple Inc. “Swift 编程语言 (Swift 3.0.1)。”电子书。 itun.es/us/jEUH0.l
-
更新了我的答案。但不幸的是,该方法并没有像预期的那样工作。我认为您应该尝试马特的回答stackoverflow.com/a/42182054/5327882
-
@ronatory 感谢您的回答,我非常感谢您的努力:) 问题是我尝试了 matt 的回答,但似乎效果不佳,我不确定可能是什么问题虽然有
标签: ios swift uibutton swift3 extension-methods