如何更改UISearchBar占位符和图像色调?

时间:2015-03-31 18:20:56

标签: ios iphone xcode swift uikit

我一直在尝试搜索结果几个小时,但我无法理解这一点。也许这是不可能的。我正在尝试更改UISearchBar的占位符文本和放大镜的色调颜色。如果重要的话,我只针对iOS 8.0+。这是我的代码以及它现在的样子:

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

a busy cat

我希望搜索和放大镜是白色的,或者可能是深绿色。

12 个答案:

答案 0 :(得分:67)

详细

  • Xcode版本10.2(10E125)
  • Swift 5

解决方案

import UIKit

extension UISearchBar {

    func getTextField() -> UITextField? { return value(forKey: "searchField") as? UITextField }
    func setText(color: UIColor) { if let textField = getTextField() { textField.textColor = color } }
    func setPlaceholderText(color: UIColor) { getTextField()?.setPlaceholderText(color: color) }
    func setClearButton(color: UIColor) { getTextField()?.setClearButton(color: color) }

    func setTextField(color: UIColor) {
        guard let textField = getTextField() else { return }
        switch searchBarStyle {
        case .minimal:
            textField.layer.backgroundColor = color.cgColor
            textField.layer.cornerRadius = 6
        case .prominent, .default: textField.backgroundColor = color
        @unknown default: break
        }
    }

    func setSearchImage(color: UIColor) {
        guard let imageView = getTextField()?.leftView as? UIImageView else { return }
        imageView.tintColor = color
        imageView.image = imageView.image?.withRenderingMode(.alwaysTemplate)
    }
}

extension UITextField {

    private class ClearButtonImage {
        static private var _image: UIImage?
        static private var semaphore = DispatchSemaphore(value: 1)
        static func getImage(closure: @escaping (UIImage?)->()) {
            DispatchQueue.global(qos: .userInteractive).async {
                semaphore.wait()
                DispatchQueue.main.async {
                    if let image = _image { closure(image); semaphore.signal(); return }
                    guard let window = UIApplication.shared.windows.first else { semaphore.signal(); return }
                    let searchBar = UISearchBar(frame: CGRect(x: 0, y: -200, width: UIScreen.main.bounds.width, height: 44))
                    window.rootViewController?.view.addSubview(searchBar)
                    searchBar.text = "txt"
                    searchBar.layoutIfNeeded()
                    _image = searchBar.getTextField()?.getClearButton()?.image(for: .normal)
                    closure(_image)
                    searchBar.removeFromSuperview()
                    semaphore.signal()
                }
            }
        }
    }

    func setClearButton(color: UIColor) {
        ClearButtonImage.getImage { [weak self] image in
            guard   let image = image,
                let button = self?.getClearButton() else { return }
            button.imageView?.tintColor = color
            button.setImage(image.withRenderingMode(.alwaysTemplate), for: .normal)
        }
    }

    func setPlaceholderText(color: UIColor) {
        attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes: [.foregroundColor: color])
    }

    func getClearButton() -> UIButton? { return value(forKey: "clearButton") as? UIButton }
}

完整样本

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.setText(color: .brown)
        searchBar.setTextField(color: UIColor.green.withAlphaComponent(0.3))
        searchBar.setPlaceholderText(color: .white)
        searchBar.setSearchImage(color: .white)
        searchBar.setClearButton(color: .red)
    }
}

结果

enter image description here enter image description here

答案 1 :(得分:30)

如果您有可以使用的自定义图像,则可以使用类似于以下内容的方式设置图像并更改占位符文本颜色:

[searchBar setImage:[UIImage imageNamed:@"SearchWhite"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];

UITextField *searchTextField = [searchBar valueForKey:@"_searchField"];    
if ([searchTextField respondsToSelector:@selector(setAttributedPlaceholder:)]) {
    UIColor *color = [UIColor purpleColor];
    [searchTextField setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"Search" attributes:@{NSForegroundColorAttributeName: color}]];
}

在该示例中,我使用了purpleColor,而您可以使用+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha方法创建自定义深绿色。

编辑:我刚刚意识到你是在迅速写作...呃。快速键入这个,所以我没有在Obj-C中留下答案。

    searchBar.setImage(UIImage(named: "SearchWhite"), forSearchBarIcon: UISearchBarIcon.Search, state: UIControlState.Normal);

    var searchTextField: UITextField? = searchBar.valueForKey("searchField") as? UITextField
    if searchTextField!.respondsToSelector(Selector("attributedPlaceholder")) {
        var color = UIColor.purpleColor()
        let attributeDict = [NSForegroundColorAttributeName: UIColor.purpleColor()]
        searchTextField!.attributedPlaceholder = NSAttributedString(string: "search", attributes: attributeDict)
    }

Swift 3.0

    var searchTextField: UITextField? = searchBar.value(forKey: "searchField") as? UITextField
    if searchTextField!.responds(to: #selector(getter: UITextField.attributedPlaceholder)) {
        let attributeDict = [NSForegroundColorAttributeName: UIColor.white]
        searchTextField!.attributedPlaceholder = NSAttributedString(string: "Search", attributes: attributeDict)
    }

答案 2 :(得分:9)

Swift 3:如果你想更改占位符,清除按钮和放大镜玻璃

    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

答案 3 :(得分:4)

您可以在不违反私人API规则的情况下更改文字的颜色:

UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.whiteColor()

答案 4 :(得分:1)

我找到了一种方法来更改搜索栏中的textfiled。 它适用于swift 3和Xcode8。

首先,继承UISearchBar类。

class CustomSearchBar: UISearchBar {

UISearchBar包含一个包含您想要的重要文本字段的视图。以下函数获取子视图中的索引。

func indexOfSearchFieldInSubviews() -> Int! {
    var index: Int!
    let searchBarView = subviews[0]
    for (i, subview) in searchBarView.subviews.enumerated() {
        if subview.isKind(of: UITextField.self) {
            index = i
            break
        }
    }
    return index
}


override func draw(_ rect: CGRect) {
    // Find the index of the search field in the search bar subviews.
    if let index = indexOfSearchFieldInSubviews() {
        // Access the search field
        let searchField: UITextField = subviews[0].subviews[index] as! UITextField
        // Set its frame.
        searchField.frame = CGRect(x: 5, y: 5, width: frame.size.width - 10, height: frame.size.height - 10)
        // Set the font and text color of the search field.
        searchField.font = preferredFont
        searchField.textColor = preferredTextColor

        // Set the placeholder and its color
        let attributesDictionary = [NSForegroundColorAttributeName: preferredPlaceholderColor.cgColor]
        searchField.attributedPlaceholder = NSAttributedString(string: preferredPlaceholder, attributes: attributesDictionary)

        // Set the background color of the search field.
        searchField.backgroundColor = barTintColor
    }

    super.draw(rect)
}

你去,享受这个。

答案 5 :(得分:1)

对Vasily Bodnarchuk的简短回复。

Swift 4 +

NSForegroundColorAttributeName已更改为NSAttributedStringKey.foregroundColor

答案 6 :(得分:1)

我做了一个Swift 4.1搜索栏扩展:

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

您可以像这样将其用于searchBar

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

答案 7 :(得分:1)

extension UISearchBar {
    var textField: UITextField? { return value(forKey: "searchField") as? UITextField }
    var placeholderLabel: UILabel? { return textField?.value(forKey: "placeholderLabel") as? UILabel }
    var icon: UIImageView? { return textField?.leftView as? UIImageView }
    var iconColor: UIColor? {
        get {
            return icon?.tintColor
        }
        set {
            icon?.image = icon?.image?.withRenderingMode(.alwaysTemplate)
            icon?.tintColor = newValue
        }
    }
}

答案 8 :(得分:0)

我无法使用上述任何解决方案。

我创建了以下UISearchBar类别,该类别适用于 iOS 8.4 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]];

重要提示:

确保调用setPlaceholderColor: AFTER 您的UISearchBar已添加到视图中并创建了其视图层次结构。

如果您以编程方式打开搜索栏,请将其命名为 AFTER 您的yesFirstResponder电话:

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

否则,如果您正在利用 UISearchBarDelegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [searchBar setPlaceholderColor:[UIColor redColor]];
}

答案 9 :(得分:0)

对于任何只是尝试更改文本并且无法查看更新的占位符的人来说,通过将其放在此处而不是viewDidLoad,它对我有用。

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.searchBar.placeholder = @"My Custom Text";
}

答案 10 :(得分:0)

刚刚找到了这个线索,对于这个年龄段的颠簸感到抱歉。但是,这有助于我解决问题,并在@m_katsifarakis答案上添加了更多内容,从而为他的现有类别添加了更多内容。

为占位符和输入文本添加其他颜色和字体支持。

这是我所支持的,仅在iOS 13上进行了测试。

const arr = 'school,room,teacher,pencil'
console.log(getJson('room', arr))
console.log(getJson('teacher', arr))
console.log(getJson('pencil', arr))

根据当前设置,使用情况(我在viewDidLoad和Appear中使用过),结果可能会有所不同:

@interface UISearchBar (ColorandFont)
- (void)setPlaceholderColor:(UIColor *)placeholderColor setPlaceholderFont:(UIFont *)placeholderFont;
- (void)setTextColor:(UIColor *)textColor setTextFont:(UIFont *)textFont;
@end
@implementation UISearchBar (ColorandFont)

//Placeholder Color
- (void)setPlaceholderColor:(UIColor *)placeholderColor setPlaceholderFont:(UIFont *)placeholderFont{
    UILabel *labelView = [self placeholderText:self];
    [labelView setTextColor:placeholderColor];
    [labelView setFont:placeholderFont];
}
- (UILabel *)placeholderText:(UIView *)view {
    for (UIView *v in [view subviews]) {
        if ([v isKindOfClass:[UILabel class]]) {
            return (UILabel *)v;
        }

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

//Text Color
- (void)setTextColor:(UIColor *)textColor setTextFont:(UIFont *)textFont{
    UITextField *textView = [self searchBarText:self];
    [textView setTextColor:textColor];
    [textView setFont:textFont];
}
- (UITextField *)searchBarText:(UIView *)view {
    for (UIView *v in [view subviews]) {
        if ([v isKindOfClass:[UITextField class]]) {
            return (UITextField *)v;
        }

        UIView *textView = [self searchBarText:v];
        if (textView) {
            return (UITextField *)textView;
        }
    }
    return nil;
}
@end

答案 11 :(得分:-3)

在Swift 4中,假设您的搜索控制器设置如下:

let searchController = UISearchController(searchResultsController: nil)

然后设置占位符文本如下:

searchController.searchBar.placeholder = "Here is my custom text"