我有一个自定义的 UIOutlineLabel 类,它在标签内的文本周围绘制轮廓。自从更新到 Swift 4 以来,我收到以下错误:
无法将类型“[String:Any]”的值转换为预期参数类型“[NSAttributedStringKey:Any]?”。
我尝试将中风文本属性更改为:
as! [NSAttributedStringKey : Any]
但这会导致运行时错误。
还有 Swift 语言运行时警告:“UIOutlineLabel setOutlineWidth 已弃用,将在 Swift 4 中删除”和“UIOutlineLabel setOutlineColor 已弃用,将在 Swift 4 中删除”。
旧代码:
import UIKit
class UIOutlineLabel: UILabel {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
var outlineWidth: CGFloat = 1
var outlineColor: UIColor = UIColor.white
override func drawText(in rect: CGRect) {
let strokeTextAttributes = [
NSAttributedStringKey.strokeColor.rawValue : outlineColor,
NSAttributedStringKey.strokeWidth : -1 * outlineWidth,
] as! [String : Any]
self.attributedText = NSAttributedString(string: self.text ?? "", attributes: strokeTextAttributes)
super.drawText(in: rect)
}
}
最佳答案
我认为你应该使用:
override func drawText(in rect: CGRect) {
let strokeTextAtrributes: [NSAttributedStringKey : Any] = [
NSAttributedStringKey.strokeColor : outlineColor,
NSAttributedStringKey.strokeWidth : -1 * outlineWidth,
]
self.attributedText = NSAttributedString(string: self.text ?? "", attributes: strokeTextAttributes)
super.drawText(in: rect)
}
因为属性参数需要一个 [NSAttributedStringKey : Any]?
类型
关于swift - 代码 9 : Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedStringKey : Any]?' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46359772/