Setting tint color for embedded UISearchbar in Nav

2019-02-17 03:11发布

问题:

I have an app that has a blue tint theme to the entire UI. I also have an embedded search bar in the Navigation Bar on my initial view. My button text color for the app is white and declare that in the app delegate using:

    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];

Problem is that this causes the embedded search bar to hide the cursor when it is selected because of the white tint affecting the search bar. I have tried to specifically set the tint of the search bar to [UIColor blueColor] using two methods but have had no luck. The two ways I have tried to refrence the UISearch bar are:

    [self.navigationController.searchDisplayController.searchBar setTintColor:[UIColor blueColor]];

and

    [searchBar setTintColor:[UIColor blueColor]]

The searchBar should be referenced properly.

Nothing I do to these outlets affect the embedded search bar at all.

回答1:

Had the same problem. Solved it by using this code after embedding the search bar into navigation bar.

    self.navigationItem.titleView.tintColor = [UIColor blueColor];

Probably not the best solution, but it works.



回答2:

Under iOS 7 (and beyond, presumably), you'll probably want to set barTintColor on your navigation and search bars to change the wrapping UI color.

[searchBar setBarTintColor:[UIColor blueColor]]

For the same appearance, you will want to use barTintColor when in iOS 7+ and use tintColor for anything earlier. If you try changing tintColor in iOS 7, you will change your cursor color, resulting in that "hidden" cursor issue you mention.



回答3:

If you subclass it, you also gain the ability to control the statusBarStyle.

import UIKit

class SearchController: UISearchController {
    override func viewDidLoad() {
        super.viewDidLoad()
        searchBar.tintColor = UIColor.tintColor()
        searchBar.barTintColor = UIColor.backgroundColor()
    }

    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return .LightContent
    }
}