Bhumit Mehta Bhumit Mehta - 3 months ago 47
Objective-C Question

UITextField from UISearchBar in iOS 7.1

I am accessing textfield of searchbar . This keeps changing

For iOS 6 i am using

textField = [searchbar.subviews objectAtIndex:1];


It changed in iOS 7 there is a view and in that there was a subview from which we can get textField , So i am using following code for iOS 7 or greater iOS

UIView *searchbarview = [searchbar.subviews objectAtIndex:0];
NSLog(@"searchbarview.subviews Array is %@",searchbarview.subviews.description);
textField = (UITextField *)[searchbarview.subviews objectAtIndex:1];


Now since iOS 7.1 the searchbarview has only one subview which is UISearchBarBackground unlike iOS 7.0 where it has two subviews, So i am not able to get textField even if i iterate through all the subviews using a for loop

Can anyone help me with this
Thanks,

EDIT
Here is the log of array returned by searchbarview.subviews , you can see it returns only 1 object which is UISearchBarBackground , so i am wondering where is UITextField object

searchbarview.subviews Array is (
"<UISearchBarBackground: 0xe6bc9d0; frame = (0 0; 768 50); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0xe6bcb20>>"
)

Answer

I've tested on simulator of iOS 7.1. I see structure of UISearchBar like this:

===============================================

UISearchBar

++ UIView

++++ UISearchBarBackground

++++ UISearchBarTextField (This is UITextField object)

++++++++ _UISearchBarSearchFieldBackgroundView

++++++++ UIImageView

===============================================

take from Spark Inspector

So on iOS 7.1, you can get UITextField like this:

UIView *subviews = [searchbar.subviews lastObject];
UITextField *textView = (id)[subviews.subviews objectAtIndex:1];

===============================================

UPDATE

If your UISearchBar is in a UIViewController, try your code in method viewDidLoad or viewWillAppear!

Don't look for UITextField as soon as you create UISearchBar (look for after UISearchBar has already appeared on screen)

Comments