You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:自定义UIButton的UIBarButtonItem禁用时文本颜色保持不变

解决方案

当弹出UIAlertController时,系统会自动将导航栏中的自定义按钮标记为禁用状态,导致按钮文本颜色变为默认浅灰色。要让文本始终保持红色,只需显式指定按钮禁用状态下的前景色即可,以下是两种实现方式:

方式一:通过UIButton.Configuration设置

在按钮配置中直接指定disabledForegroundColor与正常状态颜色一致:

func createAddButton() -> UIBarButtonItem {
    var configuration = UIButton.Configuration.plain()
    configuration.title = "TEST"
    configuration.baseForegroundColor = .red
    // 设置禁用状态的前景色为红色
    configuration.disabledForegroundColor = .red
    configuration.background.backgroundColor = .white
    let button = UIButton(configuration: configuration)
    let barButton = UIBarButtonItem(customView: button)
    return barButton
}

方式二:直接给UIButton设置全状态标题颜色

绕过配置,直接为按钮的所有状态(包括禁用态)设置标题颜色:

func createAddButton() -> UIBarButtonItem {
    let button = UIButton(type: .system)
    button.setTitle("TEST", for: .normal)
    // 为正常、禁用等所有状态设置红色标题
    button.setTitleColor(.red, for: .normal)
    button.setTitleColor(.red, for: .disabled)
    button.backgroundColor = .white
    let barButton = UIBarButtonItem(customView: button)
    return barButton
}

两种方式都能确保弹出弹窗时,按钮文本始终保持红色,不会因禁用状态改变颜色。

内容的提问来源于stack exchange,提问作者Artem Bakanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 04:10:58