如何更改UISearchBar占位符和图像色彩的颜色?
我一直在尝试search结果几个小时,但我不明白这一点。 也许这是不可能的。 我试图改变UISearchBar的占位符文本和放大镜的色调颜色。 如果有问题,我只针对iOS 8.0+。 这里是我的代码和现在的样子:
let searchBar = UISearchBar() searchBar.placeholder = "Search" searchBar.searchBarStyle = UISearchBarStyle.Minimal searchBar.tintColor = UIColor.whiteColor()
我希望search和放大镜是白色的,或者是深绿色的。
如果您有可以使用的自定义图像,则可以使用类似于以下内容的方式设置图像并更改占位符文本颜色:
[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
方法来创build您自定义的深绿色。
编辑:我只是意识到你正在迅速写它…呃。 快速input这个,所以我没有把答案留在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) }
Swift 4 / xcode 9.0,Swift 3 / xcode 8.2.1
UISearchBar自定义示例
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扩展( 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 } }
用法
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) } }
结果
斯威夫特3:如果你想改变占位符,清除button和放大镜玻璃
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()
我find了一种方法来更改search栏中的文本。 它工作在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) }
你去,享受这一点。
我无法使用上述任何解决scheme正常工作。
我创build了以下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
用法 :
[mySearchBar setPlaceholderColor:[UIColor redColor]];
重要的提示:
确保你调用了setPlaceholderColor:在你的UISearchBar被添加到视图之后,并创build了它的视图层次结构。
如果以编程方式打开search栏,请在您的becomeFirstResponder调用之后调用它,如下所示:
[mySearchBar becomeFirstResponder]; [searchBar setPlaceholderColor:[UIColor redColor]];
否则,如果您正在利用UISearchBarDelegate :
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar { [searchBar setPlaceholderColor:[UIColor redColor]]; }
对瓦西里Bodnarchuk伟大的答案小更新。
Swift 4+
NSForegroundColorAttributeName
已被更改为NSAttributedStringKey.foregroundColor