How to change the position of a UITextField in a UISearchBar?

Is there a way to move a UITextField inside a UISearchBar? I would move the UITextField a bit inside the UISearchBar.

+7
source share
2 answers

The UITextField approach no longer works, possibly due to the restyling of the UISearchBar. The UISearchBar resizes the UITextField when it is displayed on the screen, which invalidates all manipulations with the UITextField.

However, I found that the UISearchBar responds to the setContentInset: method (tested on iOS 5.0.1). It adjusts the insertion distance from the closing view.

The result is a complex approach, including 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 code above resizes the contentInset UISearchBar (actually UITextField) using the CGRect specified in the anInsets parameter. Parent if-statement ( respondsToSelector: saves itself from changing this behavior in newer 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) } 
+12
source

Swift 4+

You can try this.

 searchBar.searchTextPositionAdjustment = UIOffset(horizontal: 5, vertical: 0) 

It does not move textField, but it moves text. That should be enough for most people.

+2
source

Source: https://habr.com/ru/post/893366/


All Articles