Change UISearchBar magnify icon color and position

2019-07-09 03:46发布

问题:

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.

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:

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.

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

回答1:

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:



回答2:

@Michael - Thanks for all the help. I managed to grab the UISearchBar's UITextField:

func customizeSearchBar()
{
    for subview in srcRegimenSearchBar.subviews
    {
        for view in subview.subviews
        {
            if let searchField = view as? UITextField
            {
                let imageView = UIImageView()
                let image = UIImage(named: "SearchBarIcon.png")

                imageView.image = image;
                imageView.frame = CGRectMake(0, 0, 0, 0)

                /*imageView.frame = CGRectMake(100, 0, 20, 19)*/

                searchField.leftView = imageView
                searchField.leftViewMode = UITextFieldViewMode.Always
            }
        }
    }
}

I wanted to change the position since I have access to the frame but it seems only the the top and height can be modified, at least the way I tried so I set the height and width to 0 (I couldn't find a way to make it nil or remove it completely) and I added an UIImageView with the new icon over in the left side of the UISearchbar and added a custom horizontal offset for the tint.

Not the best solution out there, I'm sure of it, but for now it works.