使用其他值在swift中初始化属性

时间:2015-02-07 10:59:21

标签: swift

是否可以使用其他值/属性在swift中初始化属性,例如:一个UIButton,UILabel,......?

我很想拥有这样的东西:

let myLabel = UILabel() {
    font = UIFont(...)
    textColor = ...
    ...
}

4 个答案:

答案 0 :(得分:2)

这是一个很好的功能,可以在C#中使用(也可能在其他语言中使用),但很遗憾在swift中不可用 - 我想不出任何模仿这种行为的解决方法。

答案 1 :(得分:1)

这样的事情怎么样?

func config<T>(obj: T, configure: T -> Void) -> T {
    configure(obj)
    return obj
}

let myLabel = config(UILabel(...)) {
    $0.font = UIFont(...)
    $0.textColor = ...
    ...
}

答案 2 :(得分:0)

不知道这是否有效,但您可以尝试使用didSet方法

let myLabel = UILabel() {
    didSet {
        myLabel.font = UIFont(...)
        myLabel.textColor = UIColor.blackColor()
    }
}

答案 3 :(得分:0)

您可以使用闭包初始化,该闭包返回您声明的类型的值,并使用()执行它:

let myLabel: UILabel = {
    let theLabel = UILabel()
    theLabel.font = UIFont(...)
    theLabel.textColor = ...
    ...
    return theLabel
}()

请注意,您必须在=

之前显式声明值类型