XCode 9:无法转换类型' [String:Any]'预期的参数类型' [NSAttributedStringKey:Any]?'

时间:2017-09-22 08:03:28

标签: swift xcode uilabel

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

我尝试将strokeTextAttributes更改为:

as! [NSAttributedStringKey : Any] 

但这会导致运行时错误。

还有一个不推荐使用的UiftutlineLabel setOutlineWidth的Swift语言运行时警告,并且将在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)
    }
}

1 个答案:

答案 0 :(得分:2)

我认为你应该使用:

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]?类型