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:
我已经尝试搜索结果好几个小时了,但是我搞不清楚。也许这是不可能的。我想改变占位符文本的颜色以及UISearchBar的放大镜。我只针对iOS 8.0+。这是我的代码,现在的样子是:
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.
我希望搜索和放大镜是白色的,或者是深绿色的。
9 个解决方案
#1
26
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)红色绿色:(CGFloat)绿色蓝色:(CGFloat)蓝色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.
编辑:我刚意识到你是用swift写的……咄。快速打印出来,这样我就不会在objc中留下答案。
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)
}
#2
53
Swift 4/xcode 9.0, Swift 3/xcode 8.2.1
Swift 4/xcode 9.0, Swift 3/xcode 8.2.1
UISearchBar customising sample
UISearchBar extension
UISearchBar扩展
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://*.com/a/40884483/4488252)
用户界面图像扩展(https://*.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
#3
7
Swift 3: If you want to change the placeholder, clearbutton and magnifier glass
Swift 3:如果您想更改占位符、clearbutton和放大镜
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
#4
4
You can change the color of the text without violating the private api rule:
您可以更改文本的颜色,而不违反私有api规则:
UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.whiteColor()
#5
1
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. Following function get the index in subviews.
UISearchBar包含一个视图,它有你想要的重要的textfield。下面的函数获取子视图中的索引。
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.
好了,尽情享受吧。
#6
0
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类别,在ios8.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.
确保您调用了setPlaceholderColor:在您的UISearchBar被添加到视图并创建了视图层次结构之后。
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]];
}
#7
0
Small update to Vasily Bodnarchuk's great answer.
Vasily Bodnarchuk的伟大答案的小更新。
Swift 4+
斯威夫特4 +
NSForegroundColorAttributeName
has been changed to NSAttributedStringKey.foregroundColor
NSForegroundColorAttributeName已改为NSAttributedStringKey.foregroundColor
#8
0
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对我起了作用。
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
self.searchBar.placeholder = @"My Custom Text";
}
#9
-1
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"
#1
26
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)红色绿色:(CGFloat)绿色蓝色:(CGFloat)蓝色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.
编辑:我刚意识到你是用swift写的……咄。快速打印出来,这样我就不会在objc中留下答案。
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)
}
#2
53
Swift 4/xcode 9.0, Swift 3/xcode 8.2.1
Swift 4/xcode 9.0, Swift 3/xcode 8.2.1
UISearchBar customising sample
UISearchBar extension
UISearchBar扩展
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://*.com/a/40884483/4488252)
用户界面图像扩展(https://*.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
#3
7
Swift 3: If you want to change the placeholder, clearbutton and magnifier glass
Swift 3:如果您想更改占位符、clearbutton和放大镜
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
#4
4
You can change the color of the text without violating the private api rule:
您可以更改文本的颜色,而不违反私有api规则:
UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.whiteColor()
#5
1
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. Following function get the index in subviews.
UISearchBar包含一个视图,它有你想要的重要的textfield。下面的函数获取子视图中的索引。
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.
好了,尽情享受吧。
#6
0
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类别,在ios8.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.
确保您调用了setPlaceholderColor:在您的UISearchBar被添加到视图并创建了视图层次结构之后。
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]];
}
#7
0
Small update to Vasily Bodnarchuk's great answer.
Vasily Bodnarchuk的伟大答案的小更新。
Swift 4+
斯威夫特4 +
NSForegroundColorAttributeName
has been changed to NSAttributedStringKey.foregroundColor
NSForegroundColorAttributeName已改为NSAttributedStringKey.foregroundColor
#8
0
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对我起了作用。
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
self.searchBar.placeholder = @"My Custom Text";
}
#9
-1
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"