gpt4 book ai didi

ios - 向没有文本的 UIButton 添加填充

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

我有一个 36x36 的 UIButton,我想添加填充(本质上像 CSS),以便可触摸区域为 the recommended 44x44 .

我尝试通过 Interface Builder 添加边缘插入,也使用下面的代码,但我尝试过的任何方法都没有增加可触摸区域。

resetButton.contentEdgeInsets.top = 50
resetButton.contentEdgeInsets.left = 50

边缘插入仅适用于包含文本的按钮吗?

更新:

  • 我已尝试设置 contentEdgeInsetsimageEdgeInsetstitleEdgeInsets 但无济于事。

  • 我可以通过编辑实际图像并增加图标周围的边框来扩展可触摸区域。 (这不是首选方式,但如果我找不到其他解决方案,我可能会走这条路。)

最佳答案

我用 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)

关于ios - 向没有文本的 UIButton 添加填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36316461/

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