iOS 11 customise search bar in navigation bar

前端 未结 7 1123
自闭症患者
自闭症患者 2020-11-28 19:26

I want to change the color of the text and icon in the iOS 11 searchbar when it is embedded in the navigation bar. So placeholder text, search text and search icon.

相关标签:
7条回答
  • 2020-11-28 20:03

    Put

    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSForegroundColorAttributeName: UIColor.white]

    and

    UISearchBar.appearance().tintColor = UIColor.white in the AppDelegate.

    Alternatively, put them both in [UIViewController viewDidLoad:]

    0 讨论(0)
  • 2020-11-28 20:04

    In addition to Darko's answer. In my case I need to get pure white search textfield color. Also I need a custom borderLine and cornerRadius. So if I just set background color to white, set custom corner radius and custom border line I've got something like this.

    The problem is that the search bar has some subviews and I've just removed them. Here is my code:

    @interface YourViewController () <UISearchBarDelegate, UISearchControllerDelegate>
    // your properties
    @property (nonatomic,strong) UISearchController *searchController;
    @property (nonatomic,strong) UISearchBar *searchBar;
    @end
    
    - (void)viewDidLoad {
    [super viewDidLoad];
    
    _searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultsTableController];
    _searchController.delegate = self;
    _searchController.searchBar.delegate = self;
    _searchBar = self.searchController.searchBar;
    
    if (@available(iOS 11.0, *)) {
    
        UITextField *searchTextField = [_searchBar valueForKey:@"searchField"];
    if (searchTextField != nil) {
            searchTextField.layer.cornerRadius = 4.f;
            searchTextField.layer.borderWidth = 1.f;
            searchTextField.clipsToBounds = YES;
    
            for (UIView *subView in searchTextField.subviews) {
                [subView removeFromSuperview];
            }
    }
    
    // Color for "Cancel" button
        _searchBar.tintColor = [UIColor blackColor];
    // Add searchController to navgationBar
        _navigationItem.searchController = _searchController;
    // Hide searchBar when scroll
        _navigationItem.hidesSearchBarWhenScrolling = YES;
    }
    }
    

    Now I've got a searchBar with pure white background, custom cornerRadius, custom border width. Also I've disabled grey highlight when tap.

    0 讨论(0)
  • 2020-11-28 20:05

    This code changes the background color of the text field

    Swift 4

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
            //background color of text field
             UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = .cyan
    
            }
    

    edited: sample of a UISearchBar in cyan

    0 讨论(0)
  • 2020-11-28 20:06

    my two cents for Swift 4.x, lightly cleaned up.

    Add in controller or App Delegate:

    appearance.backgroundColor = .green
    let myFont = UIFont.italicSystemFont(ofSize: 12)
    let attribs = [
        NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue): myFont,
        NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue): UIColor.red
    ]
    
    appearance.defaultTextAttributes =  attribs
    

    in controller:

    self.searchBar.barTintColor = .blue
    

    You will get Blue background, green search bar background, red italic font:

    0 讨论(0)
  • 2020-11-28 20:08

    I just found out how to set also the rest of them: (with some help of Brandon, thanks!)

    The "Cancel" text:

    searchController.searchBar.tintColor = .white
    

    The search icon:

    searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.search, state: .normal)
    

    The clear icon:

    searchController.searchBar.setImage(UIImage(named: "my_search_icon"), for: UISearchBarIcon.clear, state: .normal)
    

    The search text:

    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedStringKey.foregroundColor.rawValue: UIColor.white]
    

    Thanks for the help @Brandon!

    The placeholder:

    UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).attributedPlaceholder = NSAttributedString(string: "placeholder", attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
    

    The white background:

    let searchController = UISearchController(searchResultsController: nil)
    searchController.delegate = self
    
    let searchBar = searchController.searchBar
    searchBar.tintColor = UIColor.white
    searchBar.barTintColor = UIColor.white
    
    if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
        textfield.textColor = UIColor.blue
        if let backgroundview = textfield.subviews.first {
    
            // Background color
            backgroundview.backgroundColor = UIColor.white
    
            // Rounded corner
            backgroundview.layer.cornerRadius = 10;
            backgroundview.clipsToBounds = true;
        }
    }
    
    if let navigationbar = self.navigationController?.navigationBar {
        navigationbar.barTintColor = UIColor.blue
    }
    
    navigationItem.searchController = searchController
    navigationItem.hidesSearchBarWhenScrolling = false
    

    Taken from here.

    0 讨论(0)
  • 2020-11-28 20:17

    I tried Daroko solution, but i had a problem when changing the background to pure white color (it’s was grey). My solution was to use the setSearchFieldBackgroundImage. also i don't want to rely on apple struct for getting the UITextField

      if #available(iOS 11.0, *) {
         let whiteImage = UIImage(color: UIColor.white, size: CGSize(width: searchController.searchBar.layer.frame.width, height: searchController.searchBar.layer.frame.height))
         searchController.searchBar.setSearchFieldBackgroundImage(whiteImage, for: .normal)
         self.navigationItem.searchController = searchController
         self.navigationItem.hidesSearchBarWhenScrolling = true
     }
    
    
    public extension UIImage {
      public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) {
        let rect = CGRect(origin: .zero, size: size)
         UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
         color.setFill()
         UIRectFill(rect)
         let image = UIGraphicsGetImageFromCurrentImageContext()
         UIGraphicsEndImageContext()
         guard let cgImage = image?.cgImage else { return nil }
         self.init(cgImage: cgImage)
    } }
    

    I used UIImage extension from : Create UIImage with solid color in Swift

    0 讨论(0)
提交回复
热议问题