0

I have simple code which is set DatePicker as input view of UIViewController

var datePicker = UIDatePicker()

override var inputView: UIView? {
    return datePicker
}

override var canBecomeFirstResponder: Bool {
    return true
}

I have to write self.resignFirstResponder on viewDidAppear to forcefully hide the keyboard (date picker ), Why UIViewController becomes first responder automatically ?

enter image description here

Prashant Tukadiya
  • 15,838
  • 4
  • 62
  • 98
  • default value of inputView is nil when you override canBecomeFirstResponder then you are telling compiler that ViewController will be FirstResponder when View will appear in window so it will call "inputView" getter property to show it at the bottom. This is same behaviour like we used to do with "UITextField". – Muhammad Waqas Bhati Mar 25 '19 at 13:33
  • @MuhammadWaqasBhati Thank you for response, Actually I am still not getting that how `canBecomeFirstResponder` calls `becomeFirstResponder` because with canBecomeFirstResponder` we are telling compiler that This class can be first responder in future not telling to become first responder as soon as screen appears. – Prashant Tukadiya Mar 25 '19 at 13:36
  • @MuhammadWaqasBhati With UItextField we have either have to tap on it or need to call becomeFirstResponder, I have never seen that UITextField automatically becomes first responder and open keyboards – Prashant Tukadiya Mar 25 '19 at 13:38

1 Answers1

0

IMHO, when you override var canBecomeFirstResponder to true, the containing viewController should be the first responder in responders chain immediately after the completion of its initiation. You may print isFirstResponder in viewDidLoad to verify my above assertion.

I would move inputView assignment to textField: didBeginEdit to avoid such issue.

Hope it helps.

Ron Liu
  • 188
  • 11