【问题标题】:UIButton highlight color overlaps text when the button is pressed按下按钮时,UIButton 突出显示颜色与文本重叠
【发布时间】:2020-10-23 02:37:03
【问题描述】:

这是我的 UIButton 的正常状态:

但是当我按下 UIButton 时,它的高亮颜色应该更改为不同的颜色。这就是我所拥有的:

所以,如果你能注意到的话,我的白色文本会与新颜色重叠。但结果我应该拥有的只是高亮的不同颜色,并且始终是白色文本。像这样:

到目前为止,我正在做的是:

  1. 在我的 xib 文件的属性检查器中,我将 Highlight Color 更改为新的。
  2. 我也在我的代码中使用了 updateButton.setTitleColor(.white, for: .highlighted),但它没有帮助。

我也看过这个问题:UIButton background color overlaps text on highlight,但接受的答案并没有太大帮助。

【问题讨论】:

    标签: ios swift uibutton


    【解决方案1】:

    类似于 myButton.setTitleColor(.white, for: .normal) 请尝试为 .highlighted 状态设置标题颜色。这应该对你有用。

    您可以参考: https://developer.apple.com/documentation/uikit/uibutton/1623993-settitlecolor

    【讨论】:

    • 嗨@Shan,感谢您的评论。这正是我正在做的。我已经更新了我的问题。
    【解决方案2】:

    这个myButton.setTitleColor(.white, for: .normal) 在突出显示时不会改变标题颜色,它是正常状态。如果要在按钮高亮时更改 textColor,则需要使用myButton.setTitleColor(.white, for: .highlighted)

    当您在情节提要中更改状态配置时

    你可以设置文字颜色

    如果它是自定义按钮,您可以覆盖 isHighlighted 方法并执行您需要的操作

    class MyButton : UIButton {
    override var isHighlighted: Bool{
        didSet {
            tintColor = isHighlighted ? UIColor.red : UIColor.white
            backgroundColor = UIColor.blue 
            .....
            // do what you need
        }
    }
    

    【讨论】:

    • 嗨,@Omer Tekbiyik,感谢您的评论。我计划现在更新我的问题,因为myButton.setTitleColor(.white, for: .highlighted) 也无济于事。
    • 这个按钮是自定义按钮吗? @莉莉亚
    • 是的,这是定制的
    • 您能分享一下您是如何声明按钮的吗? @莉莉亚
    • 哦,对不起!我没有专心。我的按钮继承了一个继承 UIButton 的自定义类,所以我现在要检查你的解决方案。谢谢!
    【解决方案3】:

    由于您的按钮是 UIView class CellButton: UIView {} 的子类,您需要在自定义 CellButton 中处理触摸开始和结束事件并处理视图的外观。如果它是 UIButton 的子类,那么它会自动为您处理 :)

    你也可以试试手势,更多信息可以参考:https://developer.apple.com/documentation/uikit/touches_presses_and_gestures/handling_uikit_gestures/handling_tap_gestures

    【讨论】:

    • 谢谢@Shan!它实际上是 UIButton 的子类,只是我不够细心。
    猜你喜欢
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 2016-10-27
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-26
    相关资源
    最近更新 更多