How to properly init passed property in subclass o

2019-08-26 07:15发布

I have a subclass of UIView that I would like to pass a property to. As much as I've tried, I don't truly understand all elements of initializing.

Here is a simplified version of my code:

class inputWithIncrementView : UIView, UITextFieldDelegate {
    var inputName : String // This is the property I want to receive and init

override init (frame : CGRect) {
    super.init(frame : frame)
    // [this is where i will use the inputName property passed on initialization] 
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder) 
}
// [other functions and stuff working fine here]
}

I have tried a number of things, but I'm getting confused between the UIView initializer and the way I normally initialize a non-subclassed class.

How do I modify this code to receive the string property, initialize it? Thanks

1条回答
别忘想泡老子
2楼-- · 2019-08-26 07:45

If you want to initialize a UIView with a custom property you must reconfigure its initializer:

class InputWithIncrementView: UIView {

    var inputName: String?

    init(inputName: String) {

        self.inputName = inputName
        super.init(frame: CGRect.zero)

    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

}
查看更多
登录 后发表回答