[英]How to change UISearchBar Placeholder and image tint color?
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.
我正在尝试更改 UISearchBar 的占位符文本和放大镜的色调。 I'm only targeting iOS 8.0+ if that matters.
如果这很重要,我只针对 iOS 8.0+。 Here's my code and what it looks like now:
这是我的代码以及它现在的样子:
let searchBar = UISearchBar()
searchBar.placeholder = "Search"
searchBar.searchBarStyle = UISearchBarStyle.Minimal
searchBar.tintColor = UIColor.whiteColor()
I'd like for the search and magnifying glass to be white, or perhaps a dark green.我希望搜索和放大镜是白色的,或者是深绿色的。
import UIKit
extension UISearchBar {
func getTextField() -> UITextField? { return value(forKey: "searchField") as? UITextField }
func set(textColor: UIColor) { if let textField = getTextField() { textField.textColor = textColor } }
func setPlaceholder(textColor: UIColor) { getTextField()?.setPlaceholder(textColor: textColor) }
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)
}
}
private extension UITextField {
private class Label: UILabel {
private var _textColor = UIColor.lightGray
override var textColor: UIColor! {
set { super.textColor = _textColor }
get { return _textColor }
}
init(label: UILabel, textColor: UIColor = .lightGray) {
_textColor = textColor
super.init(frame: label.frame)
self.text = label.text
self.font = label.font
}
required init?(coder: NSCoder) { super.init(coder: coder) }
}
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)
}
}
var placeholderLabel: UILabel? { return value(forKey: "placeholderLabel") as? UILabel }
func setPlaceholder(textColor: UIColor) {
guard let placeholderLabel = placeholderLabel else { return }
let label = Label(label: placeholderLabel, textColor: textColor)
setValue(label, forKey: "placeholderLabel")
}
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 = .default
view.addSubview(searchBar)
searchBar.placeholder = "placeholder"
searchBar.set(textColor: .brown)
searchBar.setTextField(color: UIColor.green.withAlphaComponent(0.3))
searchBar.setPlaceholder(textColor: .white)
searchBar.setSearchImage(color: .white)
searchBar.setClearButton(color: .red)
}
}
If you have a custom image you could use, you can set the image and change the placeholder text color using something similar to the following:如果您有可以使用的自定义图像,则可以使用类似于以下内容的内容设置图像并更改占位符文本颜色:
[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}]];
}
In that example I used purpleColor, instead you can use the + (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha
method to create your custom dark green color.在该示例中,我使用了 PurpleColor,而您可以使用
+ (UIColor *)colorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha
方法来创建您的自定义深绿色。
EDIT: I just realized you were writing it in swift... duh.编辑:我刚刚意识到你写得很快......呃。 Quickly typed this out so I didn't leave the answer in just Obj-C.
快速输入这个,所以我没有只在 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斯威夫特 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)
}
Swift 3: If you want to change the placeholder, clearbutton and magnifier glass 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
您可以在不违反私有 api 规则的情况下更改文本的颜色:
UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.whiteColor()
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 类别,它在iOS 8.4和10.3上正常工作:
UISearchBar+PlaceholderColor.h UISearchBar+PlaceholderColor.h
#import <UIKit/UIKit.h>
@interface UISearchBar (PlaceholderColor)
- (void)setPlaceholderColor:(UIColor *)placeholderColor;
@end
UISearchBar+PlaceholderColor.m 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.确保在将 UISearchBar 添加到视图并创建其视图层次结构之后调用 setPlaceholderColor: 。
If you open your search bar programmatically, call it AFTER your becomeFirstResponder call, as such:如果您以编程方式打开搜索栏,请在 becomeFirstResponder 调用之后调用它,如下所示:
[mySearchBar becomeFirstResponder];
[searchBar setPlaceholderColor:[UIColor redColor]];
Otherwise, if you are leveraging UISearchBarDelegate :否则,如果您正在利用UISearchBarDelegate :
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
[searchBar setPlaceholderColor:[UIColor redColor]];
}
I made a Swift 4.1 search bar extension:我做了一个 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])
}
}
}
}
}
}
You can use this for your searchBar
like this :您可以像这样将它用于您的搜索
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))
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
}
}
}
I found a way to change the textfiled in search bar.我找到了一种更改搜索栏中文本文件的方法。 It works in swift 3 and Xcode8.
它适用于 swift 3 和 Xcode8。
Firstly, subclass the UISearchBar class.首先,继承 UISearchBar 类。
class CustomSearchBar: UISearchBar {
UISearchBar include a view which has the important textfield you wanted. UISearchBar 包含一个视图,其中包含您想要的重要文本字段。 Following function get the index in subviews.
以下函数获取子视图中的索引。
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)
}
There you go, enjoy for this.你去吧,享受这个。
Small update to Vasily Bodnarchuk's great answer. Vasily Bodnarchuk 的精彩答案的小更新。
Swift 4+斯威夫特 4+
NSForegroundColorAttributeName
has been changed to NSAttributedStringKey.foregroundColor
NSForegroundColorAttributeName
已更改为NSAttributedStringKey.foregroundColor
For anybody just trying to change the text and having trouble seeing the updated placeholder, it worked for me by putting it here instead of viewDidLoad
.对于任何只是试图更改文本并且在查看更新的占位符时遇到问题的人,将它放在这里而不是
viewDidLoad
对我viewDidLoad
。
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
self.searchBar.placeholder = @"My Custom Text";
}
Just found this thread, sorry about the bump given the age.刚刚找到这个帖子,抱歉因为年龄太大了。 However it helped me in trying to fix my issue, and adding onto @m_katsifarakis answer, I added more to his existing category.
然而,它帮助我尝试解决我的问题,并添加到@m_katsifarakis 的答案中,我在他现有的类别中添加了更多内容。
Adding additional color + font support for both placeholder and input text.为占位符和输入文本添加额外的颜色 + 字体支持。
Only tested on iOS 13 as that's all I am supporting.仅在 iOS 13 上进行了测试,因为这就是我所支持的全部内容。
@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
Usage (I used in viewDidLoad and Appear) given my current setup, results may vary:使用(我在 viewDidLoad 和 Appear 中使用)鉴于我当前的设置,结果可能会有所不同:
[self.searchBar setPlaceholderColor:[UIColor lightTextColor] setPlaceholderFont:[UIFont italicSystemFontOfSize:13]];
[self.searchBar setTextColor:[UIColor whiteColor] setTextFont:[UIFont systemFontOfSize:16]];
In Swift 4, assuming your search controller is set like this:在 Swift 4 中,假设您的搜索控制器设置如下:
let searchController = UISearchController(searchResultsController: nil)
then set placeholder text as follows:然后设置占位符文本如下:
searchController.searchBar.placeholder = "Here is my custom text"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.