How to properly init passed property in subclass of UIView?

笑着哭i 提交于 2019-12-13 02:49:25

问题


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:


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)
    }

}


来源:https://stackoverflow.com/questions/48082128/how-to-properly-init-passed-property-in-subclass-of-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!