问题
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