Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property UITextField.beginningOfDocument is always nil on iOS 8, 9. Serious bug in iOS?

It seems that with iOS 8 and 9, Xcode 7 the properties beginningOfDocument and endOfDocument of UItextField are always nil whathever you do. Even worse they are not of an optional type (UITextPosition?) in Swift 2, instead they are of type UITextPosition - and still have nil value. Debuger calls it <uninitialized> instead of nil but it is the same thing as for its behaviour. To reproduce, put following code to any UIViewController:

override func viewDidAppear(animated: Bool) {
    let textField = UITextField()
    textField.text = "Hello"
    view.addSubview(textField)
    let position: UITextPosition? = textField.beginningOfDocument //beginningOfDocument is of type UITextPosition, not optional
    //following line should always succeed
    let positionUnwrapped = position! //fatal error: unexpectedly found nil while unwrapping an Optional value
}

Is this really a (huge) bug or am I missing something? Is there a workaround, perhaps some steps to fix the problem?


EDIT: Note that this problem is not answered here. The suggested fixes there do not apply to my sample code:

  1. My demonstration code does not use Interface Builder at all so Gazzini's answer does not work. Besides, Interface Builder in XCode 7 does not have property selectable for UITextView, nor does the class itself declare such property.
  2. My demonstration code adds UITextField to view hierarchy before beginningOfDocument is accessed so m1h4's answer also isn't relevant.
like image 385
Rasto Avatar asked Oct 23 '15 12:10

Rasto


1 Answers

Yes, it's a bug in the Swift declaration of beginningOfDocument. You can report it to Apple here.

It will return a valid UITextPosition after it becomes first responder.

like image 185
rob mayoff Avatar answered Oct 30 '22 02:10

rob mayoff