代码之家  ›  专栏  ›  技术社区  ›  Stephen O'Connor

如何初始化let text属性

  •  0
  • Stephen O'Connor  · 技术社区  · 8 年前

    我有一个文本属性的前景颜色,我想用在属性字符串。属性是 let 常量,我想用 UIColor 我把它传给 init

    class LocationOptions {
        let live : NSAttributedString.Key!
        let black = [NSAttributedString.Key.foregroundColor: UIColor.black]
        let grey = [NSAttributedString.Key.foregroundColor: UIColor.gray]
        let findingLocation: NSAttributedString!
        let centralLondon: NSAttributedString!
        let allLondon: NSAttributedString!
    
    
    init(color: UIColor){
            live = [NSAttributedString.Key.foregroundColor: color]
            findingLocation = NSAttributedString(string: "Finding Location...", attributes: grey)
            centralLondon = NSAttributedString(string: "Central London", attributes: black)
            allLondon = NSAttributedString(string: "All London", attributes: black)
        }
        ....
    

    有了这段代码,编译器在分配 live

    无法将“[nsattributestring.Key:UIColor]”类型的值赋给“nsattributestring.Key”类型

    如果我改变声明 到

    let live: NSAttributedString.Key.foregroundColor!
    

    当我声明时编译器出现了错误 居住

    静态let“foregroundColor”不是“nsAttributeString.Key”的成员类型

    如何初始化这样的文本属性?

    3 回复  |  直到 8 年前
        1
  •  0
  •   kathayatnk    8 年前

    这是因为它需要属性字典。

    //This is only key and you cannot assign a attribute to it 
    let live = NSAttributedString.Key! 
    
    //this is only value
    let live: NSAttributedString.Key.foregroundColor!
    

    These won't work . 让它们工作的方法如下:

    class LocationOptions {
        let live: [NSAttributedString.Key : Any]
    
        init(color: UIColor) {
            live = [NSAttributedString.Key.foregroundColor: color]
        }
    }
    
        2
  •  0
  •   Ashley Mills    8 年前

    问题就在这里

    let live : NSAttributedString.Key!
    

    live 是类型 NSAttributedString.Key!

    如果 居住

    let live : UIColor
    

    如果是属性字典,请使用:

    let live : [NSAttributedString.Key: Any]
    
        3
  •  0
  •   Papershine    8 年前

    live 作为

    let live: [NSAttributedString.Key : UIColor]!
    

    NSAttributedString.Key.foregroundColor! 不能是的类型 居住 因为它不是类型,所以它是属性。宣布 居住 [NSAttributedString.Key : UIColor] ,您可以将字典分配给它,同时可以初始化 NSAttributedString