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

使用EmptyDataSet_Swift修改按钮标题颜色时出现报错该如何解决?

问题原因

你的报错是因为给NSAttributedString.Key.foregroundColor传入了错误类型的参数:该属性要求接收UIColor类型对象,你传入的UIColor.green.cgColor属于CGColor类型,类型不匹配触发了运行时错误。

修正后的实现代码

func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> NSAttributedString? {
    let buttonTitle = "Add a Project"
    // 提前解包可选字体,避免属性字典出现空值
    guard let font = UIFont(name: "HelveticaNeue-Bold", size: 14) else {
        return NSAttributedString(string: buttonTitle, attributes: [.foregroundColor: UIColor.green])
    }
    let buttonTitleAttributes: [NSAttributedString.Key: Any] = [
        .font: font,
        .foregroundColor: UIColor.green // 直接传UIColor对象,不要加.cgColor
    ]
    let attributedButtonTitle = NSAttributedString(string: buttonTitle, attributes: buttonTitleAttributes)
    return attributedButtonTitle
}

额外注意点

  • 如果你需要同时修改按钮不同状态下的文字颜色,可以通过判断入参的state参数(normal/highlighted等)分别返回对应的富文本即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 12:27:03