设置图像/背景图像时,UIButton 标题不会突出显示
UIButton title won't highlight when an image / background image is set
我有一个带有 right-aligned 箭头图标的自定义按钮。
点击突出显示时,只有箭头图标突出显示。文本保持白色,而不是像图标那样变成灰色。
这是代码(范围在 UIButton 的子类中):
let rightIcon = #imageLiteral(resourceName: "disclosureIndicator")
setTitleColor(.white, for: .normal)
setBackgroundImage(rightIcon, for: .normal)
guard let image = backgroundImage(for: .normal) else { return }
titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: image.size.width)
我还覆盖了 backgroundRect 属性。
override func backgroundRect(forBounds bounds: CGRect) -> CGRect {
guard let image = backgroundImage(for: .normal) else {
return super.backgroundRect(forBounds: bounds)
}
return CGRect(
x: frame.width - (image.size.width + 20),
y: (frame.height / 4) + (image.size.height / 4),
width: image.size.width,
height: image.size.height)
}
我也试过设置按钮图片(即setImage(rightIcon, .normal)
)而不是设置按钮背景图片,但是没用。
我也试过将图标和标题的高亮颜色设置为灰色,但也没用。
我希望在点击按钮时突出显示文本和图标,但我似乎找不到实现此目的的方法。真的做不到吗?
将按钮类型设置为 System
而不是 Custom
解决了这个问题。现在他们都像他们应该的那样突出显示。
我有一个带有 right-aligned 箭头图标的自定义按钮。
点击突出显示时,只有箭头图标突出显示。文本保持白色,而不是像图标那样变成灰色。
这是代码(范围在 UIButton 的子类中):
let rightIcon = #imageLiteral(resourceName: "disclosureIndicator")
setTitleColor(.white, for: .normal)
setBackgroundImage(rightIcon, for: .normal)
guard let image = backgroundImage(for: .normal) else { return }
titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: image.size.width)
我还覆盖了 backgroundRect 属性。
override func backgroundRect(forBounds bounds: CGRect) -> CGRect {
guard let image = backgroundImage(for: .normal) else {
return super.backgroundRect(forBounds: bounds)
}
return CGRect(
x: frame.width - (image.size.width + 20),
y: (frame.height / 4) + (image.size.height / 4),
width: image.size.width,
height: image.size.height)
}
我也试过设置按钮图片(即setImage(rightIcon, .normal)
)而不是设置按钮背景图片,但是没用。
我也试过将图标和标题的高亮颜色设置为灰色,但也没用。
我希望在点击按钮时突出显示文本和图标,但我似乎找不到实现此目的的方法。真的做不到吗?
将按钮类型设置为 System
而不是 Custom
解决了这个问题。现在他们都像他们应该的那样突出显示。