gpt4 book ai didi

ios - 如何在 Swift 中扩展特定 UIButton 的点击区域?

转载 作者:行者123 更新时间:2023-11-29 11:48:43 25 4
gpt4 key购买 nike

在我的应用程序中,我有一个非常小的 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 - 我该怎么做?

最佳答案

不要扩大命中区域;缩小绘图区域。使按钮成为 UIButton 的子类,并在该子类中实现 rect 方法,如下所示:

class MyButton : UIButton {
override func contentRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: 30, dy: 30)
}
override func backgroundRect(forBounds bounds: CGRect) -> CGRect {
return bounds.insetBy(dx: 30, dy: 30)
}
}

现在按钮在其可见背景之外 30 点处是可点击的。

enter image description here

关于ios - 如何在 Swift 中扩展特定 UIButton 的点击区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42181550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com