Swift UIButton title突出显示时颜色会改变吗?

问题描述

我想让UIBUtton的titleColor在用户点击按钮时发生变化,如果用户按住按钮,则当前代码如下,但如果不快速点击,则UIBUtton标题的颜色会发生变化,您能否让我知道我需要在以下代码中进行哪些更改,才能仅在检测到轻击时更改titleColor:

    var resetFiltersButton: UIButton = {
        
        let button = UIButton(type: .system)
        
        button.setTitle("Clear Filters",for: .normal)
                
        button.titleLabel?.font = UIFont(name: "AppleSDGothicNeo-Bold",size: 20)
        
        button.setTitleColor(.blue,for: .normal)
        
        button.setTitleColor(.red,for: .highlighted)
        
        button.titleLabel?.numberOfLines = 1
        
        button.tag = 1
        
        button.addTarget(self,action: #selector(buttonPressed(_:)),for: .touchUpInside)
        
        button.translatesAutoresizingMaskIntoConstraints = false
        
        return button
        
    }()

   @objc func buttonPressed(_ sender: UIButton) {
        
        // MARK: - Clear Filters button pressed:
        
        if sender.tag == 1 {

}

}

解决方法

为什么不尝试在buttonPressed函数中实现它?

@objc func buttonPressed(_ sender: UIButton) {
        

      sender.setTitleColor(color: UIColorUI,for: UIControl.State)

}
,

此问题是您将setTitleColor用于.normal和.highlighted状态。

  • .normal是未单击按钮的时间。
  • 。突出显示是单击按钮时。

相反,您可以:

  1. 仅在按下(在buttonPressed中)时更新.normal颜色;或
  2. setTitleColor for .selected,在单击后并在buttonPressed中处理选择状态(添加sender.isSelected =!sender.IsSelected)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...