How to change UISearchBar Placeholder and image ti

2019-01-08 18:45发布

I've been trying search results for hours, but I can't get this figured out. Perhaps it isn't possible. I'm trying to change the tint color of the placeholder text and magnifying glass of a UISearchBar. I'm only targeting iOS 8.0+ if that matters. Here's my code and what it looks like now:

let searchBar = UISearchBar()
searchBar.placeholder = "Search"
searchBar.searchBarStyle = UISearchBarStyle.Minimal
searchBar.tintColor = UIColor.whiteColor()

a busy cat

I'd like for the search and magnifying glass to be white, or perhaps a dark green.

11条回答
Rolldiameter
2楼-- · 2019-01-08 19:13

Made an Apple Swift version 4.1 search bar extension :-

import Foundation import UIKit extension UISearchBar{ func setTextField(placeHolderColor:UIColor = .gray,placeHolder:String = "Search Something",textColor:UIColor = .white,backgroundColor:UIColor = .black, placeHolderFont:UIFont = UIFont.systemFont(ofSize: 12.0), textFont:UIFont = UIFont.systemFont(ofSize: 12.0) ){ for item in self.subviews{ for mainView in (item as UIView).subviews{ mainView.backgroundColor = backgroundColor if mainView is UITextField{ let textField = mainView as? UITextField if let _textF = textField{ _textF.text = "success" _textF.textColor = textColor _textF.font = textFont _textF.attributedPlaceholder = NSMutableAttributedString.init(string: placeHolder, attributes: [NSAttributedStringKey.foregroundColor : placeHolderColor, NSAttributedStringKey.font : placeHolderFont]) } } } } } }

Then you can use this for your searchBar like this :- controller.searchBar.setTextField(placeHolderColor: .white, placeHolder: "Search A Pet", textColor: .white, backgroundColor: .green, placeHolderFont: UIFont.systemFont(ofSize: 14.0), textFont: UIFont.systemFont(ofSize: 14.0))

Hope this contribution will work for my other friends :) Happy coding!!

查看更多
smile是对你的礼貌
3楼-- · 2019-01-08 19:14

Swift 4/xcode 9.0, Swift 3/xcode 8.2.1

UISearchBar customising sample

UISearchBar extension

import UIKit

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 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 = 6

            case .prominent, .default:
                textField.backgroundColor = color
            }
        }
    }

    func setPlaceholderTextColor(color: UIColor) {

        if let textField = getSearchBarTextField() {
            textField.attributedPlaceholder = NSAttributedString(string: self.placeholder != nil ? self.placeholder! : "", attributes: [NSForegroundColorAttributeName: 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)
            }
        }
    }

    func setSearchImageColor(color: UIColor) {

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

UIImage extension (https://stackoverflow.com/a/40884483/4488252)

import UIKit

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
    }
}

Usage

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let searchBar = UISearchBar(frame: CGRect(x: 0, y: 20, width: UIScreen.main.bounds.width, height: 44))
        searchBar.searchBarStyle = .minimal
        view.addSubview(searchBar)

        searchBar.placeholder = "placeholder"
        searchBar.setTextColor(color: .brown)
        searchBar.setTextFieldColor(color: UIColor.green.withAlphaComponent(0.3))
        searchBar.setPlaceholderTextColor(color: .white)
        searchBar.setSearchImageColor(color: .white)
        searchBar.setTextFieldClearButtonColor(color: .red)
    }
}

Result

enter image description here enter image description here

查看更多
祖国的老花朵
4楼-- · 2019-01-08 19:15

In Swift 4, assuming your search controller is set like this:

let searchController = UISearchController(searchResultsController: nil)

then set placeholder text as follows:

searchController.searchBar.placeholder = "Here is my custom text"
查看更多
男人必须洒脱
5楼-- · 2019-01-08 19:21

I could not make it work properly with any of the above solutions.

I created the following UISearchBar category which works properly on iOS 8.4 and 10.3:

UISearchBar+PlaceholderColor.h

#import <UIKit/UIKit.h>

@interface UISearchBar (PlaceholderColor)

- (void)setPlaceholderColor:(UIColor *)placeholderColor;

@end

UISearchBar+PlaceholderColor.m

#import "UISearchBar+PlaceholderColor.h"

@implementation UISearchBar (PlaceholderColor)

- (void)setPlaceholderColor:(UIColor *)placeholderColor {
    UILabel *labelView = [self searchBarTextFieldLabelFromView:self];
    [labelView setTextColor:placeholderColor];
}

- (UILabel *)searchBarTextFieldLabelFromView:(UIView *)view {
    for (UIView *v in [view subviews]) {
        if ([v isKindOfClass:[UILabel class]]) {
            return (UILabel *)v;
        }

        UIView *labelView = [self searchBarTextFieldLabelFromView:v];
        if (labelView) {
            return (UILabel *)labelView;
        }
    }

    return nil;
}

@end

USAGE:

[mySearchBar setPlaceholderColor:[UIColor redColor]];

IMPORTANT NOTE:

Make sure that you call setPlaceholderColor: AFTER your UISearchBar has been added to the view and has created its view hierarchy.

If you open your search bar programmatically, call it AFTER your becomeFirstResponder call, as such:

[mySearchBar becomeFirstResponder];
[searchBar setPlaceholderColor:[UIColor redColor]];

Otherwise, if you are leveraging UISearchBarDelegate:

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setPlaceholderColor:[UIColor redColor]];
}
查看更多
聊天终结者
6楼-- · 2019-01-08 19:22

Swift 3: If you want to change the placeholder, clearbutton and magnifier glass

    let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as? UITextField
    textFieldInsideSearchBar?.textColor = UIColor.white

    let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
    textFieldInsideSearchBarLabel?.textColor = UIColor.white

    let clearButton = textFieldInsideSearchBar?.value(forKey: "clearButton") as! UIButton
    clearButton.setImage(clearButton.imageView?.image?.withRenderingMode(.alwaysTemplate), for: .normal)
    clearButton.tintColor = UIColor.white

    let glassIconView = textFieldInsideSearchBar?.leftView as? UIImageView

    glassIconView?.image = glassIconView?.image?.withRenderingMode(.alwaysTemplate)
    glassIconView?.tintColor = UIColor.white
查看更多
唯我独甜
7楼-- · 2019-01-08 19:23

You can change the color of the text without violating the private api rule:

UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.whiteColor()
查看更多
登录 后发表回答