代码之家  ›  专栏  ›  技术社区  ›  Fawwad Ahmed

无法转换类型“[字符串:AnyObject]?”的值到预期的参数类型“[NSAttribute StringKey:Any]?”

  •  21
  • Fawwad Ahmed  · 技术社区  · 9 年前

    '[String : AnyObject]?' '[NSAttributedStringKey : Any]?' ?

    open class func drawText(context: CGContext, text: String, point: CGPoint, 
    align: NSTextAlignment, attributes: [String : AnyObject]?)
    {
        var point = point
    
        if align == .center
        {
            point.x -= text.size(withAttributes: attributes).width / 2.0
        }
        else if align == .right
        {
            point.x -= text.size(withAttributes: attributes).width
        }
    
        NSUIGraphicsPushContext(context)
    
        (text as NSString).draw(at: point, withAttributes: attributes)
    
        NSUIGraphicsPopContext()
    }
    
    3 回复  |  直到 8 年前
        1
  •  29
  •   Charles Srstka    8 年前

    这是Swift 4的新功能。所有采用字符串标识符和/或字典键的Cocoa方法现在都有自己的键类型。这样做的原因是为了增加一点类型安全性在旧体制中,可能会意外通过 String 常量错误,本应与其他API一起使用,但现在在Swift 4中,这将导致编译错误。

    open class func drawText(context: CGContext, text: String, point: CGPoint,
        align: NSTextAlignment, attributes: [NSAttributedString.Key : Any]?)
    

    编辑: 更新为Swift 4.2! NSAttributedStringKey NSAttributedString.Key .

        2
  •  5
  •   glyvox    9 年前

    你的 atrribute drawText

    改变

    open class func drawText(context: CGContext, text: String, point: CGPoint, align: NSTextAlignment, attributes: [String : AnyObject]?)
    

    到

    open class func drawText(context: CGContext, text: String, point: CGPoint, align: NSTextAlignment, attributes: [NSAttributedStringKey : Any]?)
    
        3
  •  -1
  •   Flarosa    8 年前

    更改方法参数可以修复该方法中的错误,但会将问题推到该方法的所有调用方,这些调用方现在都有相同的问题。

    推荐文章