开发者

How can I change a UITextField position in UISearchBar?

开发者 https://www.devze.com 2023-03-22 12:05 出处:网络
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 d

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号