简体   繁体   中英

How to change UISearchController SearchBar Colour in iOS 11

I want to customize background color and text color of the search bar, I have tried following code for the make customize but no luck.

extension UISearchBar {

    private func getViewElement<T>(type: T.Type) -> T? {
        let svs = subviews.flatMap { $0.subviews }
        guard let element = (svs.filter { $0 is T }).first as? T else { return nil }
        return element
    }

    func getSearchBarTextField() -> UITextField? {
        return getViewElement(type: UITextField.self)
    }

    func getSearchBarButton() -> UIButton? {
        return getViewElement(type: UIButton.self)
    }

    func setTextColor(color: UIColor) {
        if let textField = getSearchBarTextField() {
            textField.textColor = color
        }
    }

    func setTextFieldColor(color: UIColor) {
        if let textField = getViewElement(type: UITextField.self) {
            switch searchBarStyle {
            case .minimal:
                textField.layer.backgroundColor = color.cgColor
                textField.layer.cornerRadius = 18.0
                if let backgroundview = textField.subviews.first {
                    backgroundview.layer.cornerRadius = 18.0;
                    backgroundview.clipsToBounds = true;
                }
            case .prominent, .default:
                textField.backgroundColor = color
            }
        }
    }

    func setPlaceholderTextColor(color: UIColor) {
        if let textField = getSearchBarTextField() {
            textField.attributedPlaceholder = NSAttributedString(string: self.placeholder != nil ? self.placeholder! : "", attributes: [NSAttributedStringKey.foregroundColor: color])
        }
    }

    func setTextFieldClearButtonColor(color: UIColor) {
        if let textField = getSearchBarTextField() {
            let button = textField.value(forKey: "_clearButton") as! UIButton
            if let image = button.imageView?.image {
                button.setImage(image.transform(withNewColor: color), for: .normal)
            }else{
                //button.setImage(#imageLiteral(resourceName: "icon-hotel"), for: .normal)
            }
        }
        if let btn = getSearchBarButton() {
            let button = btn.value(forKey: "_clearButton") as! UIButton
            if let image = button.imageView?.image {
                button.setImage(image.transform(withNewColor: color), for: .normal)
            }else{
                //button.setImage(#imageLiteral(resourceName: "icon-hotel"), for: .normal)
            }
        }

    }

    func setSearchImageColor(color: UIColor) {
        if let imageView = getSearchBarTextField()?.leftView as? UIImageView {
            imageView.image = imageView.image?.transform(withNewColor: color)
        }
    }
}

extension UIImage {

    func transform(withNewColor color: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, scale)

        let context = UIGraphicsGetCurrentContext()!
        context.translateBy(x: 0, y: size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.setBlendMode(.normal)

        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        context.clip(to: rect, mask: cgImage!)

        color.setFill()
        context.fill(rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return newImage
    }
}

It is working only when I used UISearchbar only, but not working when it is UISearchController.

Please find below image for more understanding. I need text/placeholder color white. and clear/search image color white.

在此处输入图片说明 在此处输入图片说明

I have used the code below.

self.title = "Skills"
        self.navigationController?.navigationBar.prefersLargeTitles = true
        self.navigationController?.isNavigationBarHidden = false
        self.navigationController?.navigationBar.barTintColor = UIColor.hexString("6EC280") //light green

        self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
        self.navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]

        //SEARCH BAR CUSTOMIZATION
        let btnBack = UIButton(frame: CGRect(x: 0, y: 0, width: 30.0, height: 50.0))
        btnBack.setImage(#imageLiteral(resourceName: "chevron-back"), for: .normal)
        btnBack.addTarget(self, action: #selector(btnBack(_:)), for: .touchUpInside)
        let BarItem = UIBarButtonItem(customView: btnBack)
        navigationItem.leftBarButtonItem = BarItem

        UISearchBar.appearance().tintColor = UIColor.white
        UINavigationBar.appearance().tintColor = UIColor.white

        searchBarController.searchResultsUpdater = self
        searchBarController.obscuresBackgroundDuringPresentation = false
        navigationItem.searchController = searchBarController
        navigationItem.hidesSearchBarWhenScrolling = false
        definesPresentationContext = true

        searchBarController.searchBar.placeholder = "Search"
        searchBarController.searchBar.setTextColor(color: .white)
        searchBarController.searchBar.setPlaceholderTextColor(color: .white)
        searchBarController.searchBar.setSearchImageColor(color: .white)
        searchBarController.searchBar.setTextFieldColor(color: UIColor.hexString("549C64")) //light green
        searchBarController.searchBar.delegate = self

In your AppDelegate, in didFinishLaunchingWithOptions function add the following lines of code:

UISearchBar.appearance().tintColor = .green  // Add your color
UISearchBar.appearance().backgroundColor = .white  // Add your color

I have put the code in the main queue and its work.

DispatchQueue.main.async {
            self.searchBarController.searchBar.placeholder = "Search"
            self.searchBarController.searchBar.setTextColor(color: .white)
            self.searchBarController.searchBar.setPlaceholderTextColor(color: .white)
            self.searchBarController.searchBar.setSearchImageColor(color: .white)
            self.searchBarController.searchBar.setTextFieldColor(color: UIColor.clear) //light green
            self.searchBarController.searchBar.delegate = self
        }

Strange :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM