gpt4 book ai didi

swift4 - Swift 4转换错误-NSAttributedStringKey:任何

转载 作者:行者123 更新时间:2023-12-03 09:15:40 25 4
gpt4 key购买 nike

我最近转换了我的应用程序,但不断收到错误消息

"Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedStringKey: Any]?'


barButtonItem.setTitleTextAttributes(attributes, for: .normal)
整个代码:
 class func getBarButtonItem(title:String) -> UIBarButtonItem {
let barButtonItem = UIBarButtonItem.init(title: title, style: .plain, target: nil, action: nil)
let attributes = [NSAttributedStringKey.font.rawValue: UIFont(name: "Helvetica-Bold", size: 15.0)!, NSAttributedStringKey.foregroundColor: UIColor.white] as! [String : Any]
barButtonItem.setTitleTextAttributes(attributes, for: .normal)

return barButtonItem
}

最佳答案

为什么会出现此错误
以前,您的attributes定义为[String: Any],其中键来自Swt 4.2中的NSAttributedStringKey作为字符串或NSAttributedString.Key在迁移期间,编译器将尝试保留[String: Any]类型。但是,NSAttributedStringKey在swift 4中成为一个结构。因此,编译器尝试通过获取其原始值将其更改为字符串。
在这种情况下,setTitleTextAttributes正在寻找[NSAttributedStringKey: Any],但您提供了[String: Any]要解决此错误:
删除.rawValue并将您的attributes转换为[NSAttributedStringKey: Any]即,更改以下行

let attributes = [NSAttributedStringKey.font.rawValue:
UIFont(name: "Helvetica-Bold", size: 15.0)!,
NSAttributedStringKey.foregroundColor: UIColor.white] as! [String : Any]
let attributes = [NSAttributedStringKey.font:
UIFont(name: "Helvetica-Bold", size: 15.0)!,
NSAttributedStringKey.foregroundColor: UIColor.white] as! [NSAttributedStringKey: Any]
在Swift 4.2中
 let attributes = [NSAttributedString.Key.font:
UIFont(name: "Helvetica-Bold", size: 15.0)!,
NSAttributedString.Key.foregroundColor: UIColor.white] as! [NSAttributedStringKey: Any]

关于swift4 - Swift 4转换错误-NSAttributedStringKey:任何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46314661/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com