【问题标题】:XCode 9: Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedStringKey : Any]?'XCode 9:无法将类型“[String:Any]”的值转换为预期的参数类型“[NSAttributedStringKey:Any]?”
【发布时间】:2017-09-22 08:03:28
【问题描述】:

我有一个 UIOutlineLabel 的自定义类,它在标签内的文本周围绘制轮廓。由于更新到 Swift 4,我收到以下错误:
无法将类型“[String:Any]”的值转换为预期的参数类型“[NSAttributedStringKey:Any]?”。

我已尝试将 strokeTextAttributes 更改为:

as! [NSAttributedStringKey : Any] 

但这会导致运行时错误。

还有“UIOutlineLabel setOutlineWidth 已弃用并将在 Swift 4 中删除”和“UIOutlineLabel setOutlineColor 已弃用并将在 Swift 4 中删除”的 Swift 语言运行时警告。

旧代码:

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)
    }
}

【问题讨论】:

    标签: swift xcode uilabel


    【解决方案1】:

    我认为你应该使用:

    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)
    }
    

    因为 attributes 参数需要 [NSAttributedStringKey : Any]? 类型

    【讨论】:

    • 感谢这解决了崩溃问题,但运行时警告“UIOutlineLabel setOutlineWidth 已弃用并将在 Swift 4 中删除”和“UIOutlineLabel setOutlineColor 已弃用并将在 Swift 4 中删除”。跨度>
    • 在调试控制台中没有出现替代品吗?
    猜你喜欢
    • 2019-09-16
    • 2019-09-15
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2016-07-27
    • 2016-07-02
    相关资源
    最近更新 更多