Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change UISearchBar magnify icon color and position

I have a UISearchBar and I would like to change the position of the initial magnify icon (the one that appears in the middle of the UISearchBar) as well as the color or icon.

So far I changed the tint and the icon image.

However, the new icon shows up only if I test the app on a simulator but on an actual device(both run iOS 9.3) it still shows the default icon.

UISearchBar.appearance().setImage(UIImage(named: "SearchbarIcon"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal)

As for the magnify icon position, I want it in the left side, where it shows up if I activate the UISearchBar.

enter image description here

enter image description here

I found quite a lot of answers around here many of the provided solutions don't work on iOS 8.0+ or are in Objective-C and I am having some problems understanding them.

I tried to add a custom background containing the icon but it shows up at the bottom of the search bar while the icon is still there:

enter image description here

The background shows up OK if I change the background offset for Y to -44 (the height of the UISearchBar) but I can no longer type since it seems the entire text field is pushed up. I also tried to change the vertical offset for the SearchText to 44 to compensate but no luck. To be honest, I am not sure what Search Text and the Background offsets are supposed to do but I decided to give them a try.

enter image description here

Is there any way to accomplish this? Or maybe a different approach?

like image 492
daydr3am3r Avatar asked Apr 12 '16 14:04

daydr3am3r


1 Answers

You can adjust the position of the search bar icon using

func positionAdjustmentForSearchBarIcon(_ icon: UISearchBarIcon) -> UIOffset

See https://developer.apple.com/library/ios/documentation/UIKit/Reference/UISearchBar_Class/#//apple_ref/occ/instm/UISearchBar/positionAdjustmentForSearchBarIcon:

like image 154
Michael Avatar answered Oct 13 '22 20:10

Michael