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:
selectable for UITextView, nor does the class itself declare such property.UITextField to view hierarchy before beginningOfDocument is accessed so m1h4's answer also isn't relevant.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With