I’m trying to emulate the behaviour of the address bar in iOS Safari – that is, if there’s text in the address bar when it’s tapped, it is selected. Much in the same way most desktop browsers work, too. I don’t want to CLEAR it on selection, merely select what’s inside, so that if the user then begins typing, it’ll clear, but the user also has the ability to edit the existing string if they want to.
I’ve tried the following, it finds the UISearchBarTextField
inside the subviews under both iOS7 and iOS6, but calling selectAll
on it doesn’t seem to have any effect. I’ve tried changing its text
property, that works fine, it’s just selectAll
that isn’t happy.
I’ve also tried changing the argument to selectAll:
to self
and a couple other things, no change, just doesn’t wanna select the text in there!
Any thoughts? Here’s my code:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
NSArray *subviews = [UIDevice isRunningiOS7OrAbove]
? [[searchBar.subviews objectAtIndex:0] subviews]
: searchBar.subviews;
for (UIView *subview in subviews) {
if ([subview conformsToProtocol:@protocol(UITextInputTraits)]) {
UITextField *textField = (UITextField *)subview;
[textField selectAll:textField];
}
}
}
EDIT
I’ve also tried this, with no joy:
for (UIView *subview in subviews) {
if ([subview conformsToProtocol:@protocol(UITextInputTraits)]) {
UITextField *textField = (UITextField *)subview;
[textField setSelectedTextRange:[textField textRangeFromPosition:[textField beginningOfDocument]
toPosition:[textField endOfDocument]]];
}
}