Как изменить цвет шрифта UISearchBar и цвет оттенка изображения?
Я пытаюсь найти результаты поиска в течение нескольких часов, но я не могу понять это. Возможно, это невозможно. Я пытаюсь изменить цвет оттенка текста заполнителя и увеличительного стекла UISearchBar. Я имею в виду только iOS 8.0+, если это имеет значение. Вот мой код и как он выглядит сейчас:
let searchBar = UISearchBar()
searchBar.placeholder = "Search"
searchBar.searchBarStyle = UISearchBarStyle.Minimal
searchBar.tintColor = UIColor.whiteColor()
![a busy cat]()
Я бы хотел, чтобы поиск и увеличительное стекло были белыми или, возможно, темно-зелеными.
Ответы
Ответ 1
Если у вас есть пользовательский образ, который вы можете использовать, вы можете установить изображение и изменить цвет текста-заполнителя, используя что-то похожее на следующее:
[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
для создания своего пользовательского темно-зеленого цвета.
EDIT: Я просто понял, что вы пишете это быстро... duh. Быстро напечатал это, поэтому я не оставил ответ только в 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
Подробнее
- Версия Xcode 11.0 (11A420a), iOS 13, swift 5
Решение
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)
}
}
Результат
![enter image description here]()
Ответ 3
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
Ответ 4
Вы можете изменить цвет текста, не нарушая правило private api:
UILabel.appearanceWhenContainedInInstancesOfClasses([UITextField.self]).textColor = UIColor.whiteColor()
Ответ 5
Я нашел способ изменить textfiled в строке поиска.
Он работает в быстрых 3 и Xcode8.
Во-первых, подкласс класса UISearchBar.
class CustomSearchBar: UISearchBar {
UISearchBar включает представление, которое имеет важное текстовое поле, которое вы хотели. Следующая функция получает индекс в 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)
}
Там вы идете, наслаждайтесь этим.
Ответ 6
Я не мог заставить его работать с любым из вышеперечисленных решений.
Я создал следующую категорию 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 добавлен в представление и создал свою иерархию представлений.
Если вы открываете панель поиска программно, назовите ее ПОСЛЕ вашего вызова startFirstResponder, как такового:
[mySearchBar becomeFirstResponder];
[searchBar setPlaceholderColor:[UIColor redColor]];
В противном случае, если вы используете UISearchBarDelegate:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
[searchBar setPlaceholderColor:[UIColor redColor]];
}
Ответ 7
Небольшое обновление для Василия Боднарчука большой ответ.
Swift 4 +
NSForegroundColorAttributeName
был изменен на NSAttributedStringKey.foregroundColor
Ответ 8
Я сделал расширение панели поиска 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))
Ответ 9
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
}
}
}
Ответ 10
Для любого, кто просто пытается изменить текст и не видит обновленного заполнителя, он работал у меня, помещая его здесь вместо viewDidLoad
.
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
self.searchBar.placeholder = @"My Custom Text";
}
Ответ 11
В Swift 4 предполагается, что ваш поисковый контроллер настроен так:
let searchController = UISearchController(searchResultsController: nil)
затем установите заполнитель текста следующим образом:
searchController.searchBar.placeholder = "Here is my custom text"