簡體   English   中英

Swift中的自定義對象類

[英]Custom object class in Swift

在我的應用中,我需要具有很多具有相似屬性的標簽。 假設它們都必須是綠色的。 我不想每次都說lbl.color = UIColor.greenColor() 如何制作自定義對象類/結構,使我可以說類似var myLbl = CustomLbl()CustomLbl是我的類)。

我不確定這是不是應該的方法 如果沒有,我用其他方式也沒問題。
此外,在我的應用程序中,我將擁有更多屬性,但我僅選擇此示例。

謝謝!

您應該使用基類來創建自己的標簽,按鈕等。

class YourLabel: UILabel {

    init(coder aDecoder: NSCoder!) { 
        super.init(coder: aDecoder) 

        //you can set your properties    
        //e.g
        self.color = UIColor.colorGreen()
}

無需子類化,您只需添加一個方法即可根據需要配置標簽:

func customize() {
    self.textColor = UIColor.greenColor()
    // ...
}

以及一個創建UILabel實例,對其進行自定義並返回的靜態函數:

static func createCustomLabel() -> UILabel {
    let label = UILabel()
    label.customize()
    return label
}

將它們放在UILabel擴展中,您就可以完成-您可以使用以下方法創建自定義標簽:

let customizedLabel = UILabel.createCustomLabel()

或將自定義應用於現有標簽:

let label = UILabel()
label.customize()

更新 :為清楚起見,必須將兩種方法放在擴展內:

extension UILabel {
    func customize() {
        self.textColor = UIColor.greenColor()
        // ...
    }

    static func createCustomLabel() -> UILabel {
        let label = UILabel()
        label.customize()
        return label
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM