Is there a way to reposition UITextField inside UISearchBar? I'd like to move UITextField inside UISearchBar up a little bit.
The UITextField approach is not working anymore, probably due to a restyling of the UISearchBar object. UISearchBar resizes its UITextField when it is presented on screen, this invalidates all manipulations on the UITextField.
However, I discovered that UISearchBar responds to the setContentInset:
method (tested on iOS 5.0.1). It adjusts the inset distance from the enclosing view.
This result in a sophisticated approach involving NSInvocation:
if([aSearchBar respondsToSelector:@selector(setContentInset:)])
{
SEL aSelector = NSSelectorFromString(@"setContentInset:");
NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[aSearchBar methodSignatureForSelector:aSelector]];
[inv setSelector:aSelector];
[inv setTarget:aSearchBar];
UIEdgeInsets anInsets = UIEdgeInsetsMake(5, 0, 5, 35);
[inv setArgument:&anInsets atIndex:2]; //arguments 0 and 1 are self and _cmd respectively, automatically set by NSInvocation
[inv invoke];
}
The above code resizes the contentInset
of the UISearchBar (effectively UITextField) using the CGRect indicated in the anInsets
parameter. The parent if-statement (respondsToSelector:
) saves yourself from changes of this behaviour in new versions of iOS.
Updated for Swift3 and iOS10:
if searchBar.responds(to: Selector("setContentInset:")) {
let aSelector = Selector("setContentInset:")
let anInset = UIEdgeInsetsMake(5, 0, 5, 35)
searchBar.perform(aSelector, with: anInset)
}
Swift 4+
You can try this.
searchBar.searchTextPositionAdjustment = UIOffset(horizontal: 5, vertical: 0)
It doesn't move the textField, but moves the text. This should be enough for most people.
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