Thursday, 15 August 2013

ios - How can I initialize a let variable using a shared init method? -


I want to set up a variable using let so that its not optional, but change There will be no need to open dirty to enter time and every time. I know that I can set it legally, but the problem inside one of the only init methods is that you override the init (codec additive: encoder) for swift Need to do initializer However, I have never made such an app that the initiator was called. It is always called init (frame: CGRact) originator. So if I did not have to override the init (coder aDecoder: NSCoder) then self.imageView = UIImageView.new () in Init (frame: CGRTact) < / Code> and I will be done, but the compiler complains that it is not even set in another init, I tried to create a sharedInit () method, which is called from both intits. , But the compiler will not let me set imageView from there because it's only read out of init methods. How should I complete all my insights in the INP mode?

SuperCoolView: UIView {imageView: UIImageView required init (encoder: NSCoder) {sharedInit () Super.init (encoder: aDecoder) Override init (frame: CGRact) {SharedInit () super.init (frame: frame)} func sharedInit () {self.imageView = UIImageView.new () // other similar share init}}
< P>

Simply use the combination of lazy initialization and private 'set':

SuperCoolView: UIView { Public Private (Set) Lazy Vari imageView: UIImageView = {// In practice, Yes More Access status // In this case, include more calculation UIImageView.new ()} () // inits w / o setting imageView}

'Private set' This is a Equals let equally; Lazy lets you start the price based on another state in the SuperCoolView example

Note that if the initialization of the image view, and others, the example But do not depend on the state, you can avoid the the lazy and can only do the initial work by closing


No comments:

Post a Comment