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

Swift 4.1中Type 'NSAttributedStringKey'无'foregroundColor'成员问题求助

解决Swift 4.1中NSAttributedStringKey没有foregroundColor成员的问题

这个错误在Swift 4.1里出现,主要是因为NSAttributedStringKey的静态属性foregroundColor在该版本的兼容性处理上和后续版本有差异,或者代码写法没适配Swift 4.1的规范。下面是几种可行的解决办法:

方法1:使用兼容的字符串常量(推荐,适配多版本)

在Swift 4.1中,你可以直接用传统的属性名常量,这种写法同时兼容Swift 3和Swift 4.x版本:

let textAttributes = [NSForegroundColorAttributeName: UIColor.white]
navigationController?.navigationBar.titleTextAttributes = textAttributes

方法2:通过rawValue初始化NSAttributedStringKey

如果你更倾向于使用NSAttributedStringKey类型,可以通过原始值来创建对应的key:

let textAttributes = [NSAttributedStringKey(rawValue: NSForegroundColorAttributeName): UIColor.white]
navigationController?.navigationBar.titleTextAttributes = textAttributes

额外注意事项

  • 确保你的文件已经导入了UIKit框架,因为NSAttributedStringKey的相关扩展是在UIKit中提供的(如果是纯Foundation场景则导入Foundation);
  • 检查项目的Swift版本设置,确认确实是4.1版本(Xcode项目设置 -> Build Settings -> Swift Language Version)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:31:41