swift - 代码 9 : Cannot convert value of type '[String : Any]' to expected argument type '[NSAttributedStringKey : Any]?'

标签 swift xcode uilabel

我有一个自定义的 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/

相关文章:

xcode - 如何让 Xcode 持续集成服务执行浅层 git 克隆?

ios - 更改特定行选择上的 UITableView 所有行的标签颜色

swift - Plist 不改变值(value) [swift]

ios - UIStackView 隐藏内部 View 时分布填充相等

ios - swift 从网址中识别资源名称和扩展名

ios - 从另一个类 Swift 调用一个类的函数

swift - 无法在没有参数的情况下调用类型 "closure"的初始值设定项

xcode - 如何使用时区在 sqlite 中格式化日期时间?

iOS FontAwesome 在另一个字符串中间

android - Android 中的 iOS UILabel 等价物?