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

丶灬走出姿态 提交于 2019-12-24 00:37:28

问题


I have a custom class of UIOutlineLabel which draws an outline around the text within a label. Since updating to Swift 4 I get the following error:
Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedStringKey : Any]?'.

I have tried changing the strokeTextAttributes to:

as! [NSAttributedStringKey : Any] 

but this results in a runtime error.

There are also the Swift Language runtime warnings of 'UIOutlineLabel setOutlineWidth is deprecated and will be removed in Swift 4' & 'UIOutlineLabel setOutlineColor is deprecated and will be removed in Swift 4'.

Old Code:

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:


I think you should use:

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

because attributes argument expects an [NSAttributedStringKey : Any]? type



来源:https://stackoverflow.com/questions/46359772/xcode-9-cannot-convert-value-of-type-string-any-to-expected-argument-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!