Search code examples
iphoneiosuikituitextfielduikeyinput

Why does -[UIKeyInput hasText] always return NO for UITextField?


Why does -[UIKeyInput hasText] always return NO for UITextField? Is this a bug with UIKit?

For example, the following test fails:

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectZero];
textField.text = @"has text";
STAssertTrue([textField hasText], @"any text is text.");

Solution

  • UITextField implements UIKeyInput through the UITextInput Protocol, which states:

    UIKeyInput protocol—Implemented to acquire the capabilities of text entry and deletion at an insertion point.

    (via: http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UITextInput_Protocol/Reference/Reference.html)

    As Mattias suggested above, it has more to do with the backing store, and is meant mainly for input through the system keyboard.

    In your example, you are manipulating the property directly and circumventing input through the keyboard. By giving the field first responder, the keyboard will be shown and hasText will return YES as expected.