Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change a UITextField position in UISearchBar?

Is there a way to reposition UITextField inside UISearchBar? I'd like to move UITextField inside UISearchBar up a little bit.

like image 541
Tuyen Nguyen Avatar asked Jul 22 '11 15:07

Tuyen Nguyen


2 Answers

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)
}
like image 66
valvoline Avatar answered Nov 03 '22 15:11

valvoline


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.

like image 38
Rakesha Shastri Avatar answered Nov 03 '22 15:11

Rakesha Shastri