简体   繁体   English

设置图片/背景图片时,UIButton标题不会突出显示

[英]UIButton title won't highlight when an image / background image is set

I have a custom button with a right-aligned arrow icon. 我有一个带有右对齐箭头图标的自定义按钮。 登录按钮默认

When it's highlighted with a tap, only the arrow icon is highlighted. 点按以突出显示时,仅箭头图标会突出显示。 The text remains white instead of turning gray like the icon does. 文本保持白色,而不是像图标一样变为灰色。

登录按钮突出显示

This is the code (scoped in a subclass of UIButton): 这是代码(位于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)

I've also overridden the backgroundRect property. 我还重写了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)
}

I've also tried setting the button image (ie setImage(rightIcon, .normal) ) instead of setting the button background image, but it didn't work. 我也尝试过设置按钮图像(即setImage(rightIcon, .normal) ),而不是设置按钮背景图像,但这没有用。

I've also tried setting the highlight color for the icon and the title to gray, but that didn't work either. 我也尝试过将图标的高亮颜色和标题设置为灰色,但这也不起作用。

I want both the text and the icon to be highlighted when the button is tapped, but I can't seem to find a way of achieving this. 我希望在点击按钮时同时突出显示文本和图标,但是我似乎找不到实现此目的的方法。 Is it genuinely impossible to do? 真的不可能做吗?

Setting the button type to System instead of Custom solved the issue. 将按钮类型设置为System而不是Custom解决此问题。 Now they both highlight like they should. 现在它们都像应有的那样突出显示。

IB属性检查器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM