XCode 9:无法将 '[String : Any]' 类型的值转换为预期的参数类型 '[NSAttributedStringKey : Any]? [英] XCode 9: Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedStringKey : Any]?'

查看:27
本文介绍了XCode 9:无法将 '[String : Any]' 类型的值转换为预期的参数类型 '[NSAttributedStringKey : Any]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]?'.

我尝试将strokeTextAttributes更改为:

I have tried changing the strokeTextAttributes to:

as! [NSAttributedStringKey : Any] 

但这会导致运行时错误.

but this results in a runtime error.

还有UIOutlineLabel setOutlineWidth is deprecated and will be removed in Swift 4"的Swift语言运行时警告&'UIOutlineLabel setOutlineColor 已弃用,将在 Swift 4 中移除'.

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'.

旧代码:

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

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

这篇关于XCode 9:无法将 '[String : Any]' 类型的值转换为预期的参数类型 '[NSAttributedStringKey : Any]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆