How can I change a UITextField position in UISearchBar?

﹥>﹥吖頭↗ 提交于 2019-12-10 12:58:26

问题


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


回答1:


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)
}



回答2:


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.



来源:https://stackoverflow.com/questions/6792495/how-can-i-change-a-uitextfield-position-in-uisearchbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!