2016-01-23 45 views
2

我試圖堅持這一點,並學習它,並在Swift中編寫一個應用程序,而不是默認爲Obj-C,雖然我一直陷在非常簡單的事情上,似乎無法在網上找到我的答案。迴歸的誘惑力很強。這是我想要做的。如何用swift創建一個自定義的UIView類?

class CircleView : UIView { 

    var title: UILabel 

    convenience init(frame: CGRect, title: String) { 

    } 

    override init(frame: CGRect) { 
     self.title = UILabel.init(frame: CGRectMake(0.0, 0.0, frame.size.width, frame.size.height)) 
     super.init(frame: frame) 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("CircleView is not NSCoding compliant") 
    } 
} 

我的目標是什麼......創建CircleView實例的人應該同時提供一個框架和一個字符串。我將如何實現這一目標?

回答

1

我覺得你很親密。便利初始化可以設置標籤,然後調用指定初始化:

class CircleView : UIView { 

    var title: UILabel 

    convenience init(frame: CGRect, title: String) { 
     self.init(frame: frame) 
     self.title.text = title 
    } 

    override init(frame: CGRect) { 
     self.title = UILabel.init(frame: CGRectMake(0.0, 0.0, frame.size.width, frame.size.height)) 
     super.init(frame: frame) 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("CircleView is not NSCoding compliant") 
    } 
} 

這裏唯一需要注意的是,有人仍然可以直接調用指定初始化,而無需爲標籤提供文本。如果你不想這樣做,我相信你可以使指定的初始值設定變爲私有的,即:

private override init(frame: CGRect) { ... } 
相關問題