The UITextField.beginningOfDocument property is always zero on iOS 8, 9. Serious bug in iOS?

It seems that with iOS 8 and 9, Xcode 7, the properties beginningOfDocument and endOfDocument UItextField always nil no matter what you do. Worse, they do not have an optional type ( UITextPosition? ) In Swift 2, instead they are of type UITextPosition - and still have a nil value. Debuger calls it <uninitialized> instead of nil , but this is the same as for its behavior. To reproduce, put the following code in 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 a really (huge) mistake or am I missing something? Is there a workaround, maybe some steps to solve the problem?


EDIT: Please note that this problem did not answer here . The proposed fixes there do not apply to my sample code:

  • My demo code doesn't use Interface Builder at all, so Gazzini's answer does n't work. In addition, Interface Builder in Xcode 7 does not have a selectable property for a UITextView , and the class itself does not declare such a property.
  • My demo code adds a UItextField to view the hierarchy before beginningOfDocument is available, so m1h4's answer doesn't matter either.
+5
source share
1 answer

Yes, this is a mistake in the Swift declaration beginningOfDocument . You can report it to Apple here .

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

+5
source

Source: https://habr.com/ru/post/1234366/


All Articles