Подтвердить что ты не робот

UISearchBar меняет цвет заполнителя

Есть ли у кого-нибудь идеи или примеры кода, как я могу изменить цвет текста текста-заполнителя UISearchBar?

4b9b3361

Ответ 1

для iOS5+ используйте прокси-сервер внешнего вида

[[UILabel appearanceWhenContainedIn:[UISearchBar class], nil] setTextColor:[UIColor redColor]];

Ответ 3

Первое решение в порядке, но если вы используете несколько UISearchBar или создаете много экземпляров, это может дать сбой. Единственное решение, которое всегда работает для меня, это использовать внешний вид прокси, но непосредственно в UITextField.

   NSDictionary *placeholderAttributes = @{
                                            NSForegroundColorAttributeName: [UIColor darkButtonColor],
                                            NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue" size:15],
                                            };

    NSAttributedString *attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.searchBar.placeholder
                                                                                attributes:placeholderAttributes];

    [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setAttributedPlaceholder:attributedPlaceholder];

Ответ 4

Вот решение для Swift:

Swift 2

var textFieldInsideSearchBar = searchBar.valueForKey("searchField") as? UITextField
textFieldInsideSearchBar?.textColor = UIColor.whiteColor()

var textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.valueForKey("placeholderLabel") as? UILabel
textFieldInsideSearchBarLabel?.textColor = UIColor.whiteColor()

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

Ответ 5

if let textFieldInsideSearchBar = searchBar.value(forKey: "searchField") as ? UITextField {
    textFieldInsideSearchBar ? .textColor = UIColor.white

    if let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as ? UILabel {
        textFieldInsideSearchBarLabel ? .textColor = UIColor.white

        if 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
}

Ответ 6

Swift 3

UILabel.appearance(whenContainedInInstancesOf: [UISearchBar.self]).textColor = UIColor.white

Ответ 7

Попробуйте это и посмотрите: (Я тестировал код ниже со Swift 4.1 - Xcode 9.3-beta4)

@IBOutlet weak var sbSearchBar: UISearchBar!

if let textfield = sbSearchBar.value(forKey: "searchField") as? UITextField {

    textfield.backgroundColor = UIColor.yellow
    textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedStringKey.foregroundColor : UIColor.red])

    textfield.textColor = UIColor.green

    if let leftView = textfield.leftView as? UIImageView {
        leftView.image = leftView.image?.withRenderingMode(.alwaysTemplate)
        leftView.tintColor = UIColor.red
    }
}

Вот результат:

enter image description here

Ответ 8

Попробуйте следующее:

[self.searchBar setValue:[UIColor whatever] forKeyPath:@"_searchField._placeholderLabel.textColor"];

Вы также можете установить это в раскадровке, выбрать строку поиска, добавить запись в соответствии с атрибутами времени выполнения пользователя:

_searchField._placeholderLabel.textColor

типа Цвет и выберите нужный цвет.

Ответ 10

Поместите это в viewDidLoad вашего viewController (работающего на iOS 9):

UITextField *searchField = [self.searchBar valueForKey:@"_searchField"]; //self.searchBar is mine targeted searchBar, replace with your searchBar reference

// Change search bar text color
searchField.textColor = [UIColor whiteColor];

// Change the search bar placeholder text color
[searchField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];

//Change search bar icon if needed
[self.searchBar setImage:[UIImage imageNamed:@"searchIcon"]
   forSearchBarIcon:UISearchBarIconSearch
              state:UIControlStateNormal];

Ответ 11

После опроса нескольких ответов я выхожу из этого, надеюсь, его помощь

for (UIView *subview in searchBar.subviews) {
    for (UIView *sv in subview.subviews) {
        if ([NSStringFromClass([sv class]) isEqualToString:@"UISearchBarTextField"]) {

            if ([sv respondsToSelector:@selector(setAttributedPlaceholder:)]) {
                ((UITextField *)sv).attributedPlaceholder = [[NSAttributedString alloc] initWithString:searchBar.placeholder attributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
            }
            break;
        }
    }
}

Ответ 12

Это решение работает на Xcode 8.2.1. с Swift 3.0.

extension UISearchBar
{
    func setPlaceholderTextColorTo(color: UIColor)
    {
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.textColor = color
        let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
        textFieldInsideSearchBarLabel?.textColor = color
    }
}

Пример использования:

searchController.searchBar.setPlaceholderTextColorTo(color: mainColor)

Ответ 13

Это старый вопрос, но для тех, кто сейчас наткнется на него, вы можете изменить значок поиска на iOS 8.x - 10.3, используя следующее:

[_searchBar setImage:[UIImage imageNamed:@"your-image-name"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];

Что касается цвета текста заполнителя, вы можете проверить мой другой ответ, в котором используется категория, здесь: UISearchBar изменить цвет закладок

Ответ 14

Попробуйте следующее:

  UITextField *searchField = [searchbar valueForKey:@"_searchField"];
  field.textColor = [UIColor redColor]; //You can put any color here.