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:
- 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
forUITextView
, nor does the class itself declare such property. - My demonstration code adds
UITextField
to view hierarchy beforebeginningOfDocument
is accessed so m1h4's answer also isn't relevant.
UITextPosition
) I would get unexpected behaviour (because it really isnil
). On iOS 8 I get the same error, same behaviour. – Mallee