使用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
相关产品推荐
相关产品推荐

