ios - Strange behaviour - instantiating a UITextField in willMoveToSuperview as opposed to didMoveToSuperview -
i'm working xcode 6.3/ios/swift 1.2. i've stumbled upon strange behaviour don't understand (coming strong oo background).
put simply, if subclass uiview , use instantiate uitextfields; in constructor, overriding didmovetosuperview, on dynamically (ie, click event)... uitextfields work expected. however, when creating uitextfield object during willmovetosuperview, seems fine... doesn't respond touch events.
this demonstrated in code below (a uiviewcontroller , subclassed uiview). i've added gesture recognizer entire view containing uitextfields. clicking of them other 1 creating during willmovetosuperview, move focus textfield, , ignore touch event (as expected). however, clicking on 1 added during willmovetosuperview fires touch event. event without touch event... textfield remains unresponsive. can explain behaviour?
import uikit class rootviewcontroller:uiviewcontroller { override func viewdidload() { super.viewdidload() self.view.frame = cgrectmake(0,0,500,500) } override func viewdidappear(animated: bool) { var uiview = extendeduiview() view.addsubview(uiview) } } class extendeduiview:uiview { internal var hasmovedtosuperview:bool = false override init (frame : cgrect) { super.init(frame : frame) } convenience init() { self.init(frame:cgrectmake(0,0,500,500)) var tf: uitextfield = uitextfield(frame: cgrect(x: 0, y: 50, width: 300, height: 40)) tf.backgroundcolor = uicolor.greencolor() tf.text = "init // ok" addsubview(tf) } required init(coder adecoder: nscoder) { fatalerror("this class not support nscoding") } override func willmovetosuperview(newsuperview: uiview?) { if (!hasmovedtosuperview) { var tf: uitextfield = uitextfield(frame: cgrect(x: 0, y: 100, width: 300, height: 40)) tf.backgroundcolor = uicolor.redcolor() tf.text = "willmovetosuperview // not ok" addsubview(tf) } } override func didmovetosuperview() { if (!hasmovedtosuperview) { var tf: uitextfield = uitextfield(frame: cgrect(x: 0, y: 150, width: 300, height: 40)) tf.backgroundcolor = uicolor.greencolor() tf.text = "didmovetosuperview // ok" addsubview(tf) hasmovedtosuperview = true addgesturerecognizer(uitapgesturerecognizer(target:self, action:selector("createtfdynamically:"))) } } func createtfdynamically(value:anyobject) { var tf: uitextfield = uitextfield(frame: cgrect(x: 0, y: 200, width: 300, height: 40)) tf.backgroundcolor = uicolor.greencolor() tf.text = "createtfdynamically // ok" addsubview(tf) } }