How do I write a custom init for a UIView subclass in Swift?

前端 未结 5 1837
野的像风
野的像风 2021-01-29 20:48

Say I want to init a UIView subclass with a String and an Int.

How would I do this in Swift if I\'m just subclassing

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-29 21:00

    The init(frame:) version is the default initializer. You must call it only after initializing your instance variables. If this view is being reconstituted from a Nib then your custom initializer will not be called, and instead the init?(coder:) version will be called. Since Swift now requires an implementation of the required init?(coder:), I have updated the example below and changed the let variable declarations to var and optional. In this case, you would initialize them in awakeFromNib() or at some later time.

    class TestView : UIView {
        var s: String?
        var i: Int?
        init(s: String, i: Int) {
            self.s = s
            self.i = i
            super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
    }
    

提交回复
热议问题