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

1

6

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.
Mallee answered 23/10, 2015 at 12:44 Comment(3)
I do not understand, if it is not an optional, why are you declaring it as an optional?Have you tried on iOS8?Sherrilsherrill
@Sherrilsherrill I declare it as an optional just to demonstrate the problem. If I did not not and just used the value (supposed to be UITextPosition) I would get unexpected behaviour (because it really is nil). On iOS 8 I get the same error, same behaviour.Mallee
Check here is already has been answered #20426548Sherrilsherrill
M
5

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.

Marcus answered 23/10, 2015 at 16:1 Comment(2)
So calling becomeFirstResponder works nicelly for most apps. But mine is keyboard extension - and calling becomeFirstResponder inside results in this error: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Received more than one main-thread continuation for the current keyboard task.' I could use UITextView instead which does not have this issue - but has another (see my question here). Looks like there is not way out of this text input hell for me...Mallee
seems to be fixed in ios 11Statement

© 2022 - 2024 — McMap. All rights reserved.