Изменение цвета текста в строке поиска в iOS 13 - PullRequest
0 голосов
/ 26 октября 2019

UI Search Bar

Я пытаюсь установить цвет для текста заполнителя внутри UISearchbar. Прямо сейчас у меня следующий код. Он не устанавливает белый цвет для текста-заполнителя на iOS 13. Он работает на iOS 12. Кажется, что-то либо сломано, либо поддержка была удалена в iOS 13?

Я много искал и пробовал несколько обходных путей, но не работает. Я также пытался установить атрибут текста для текстового поля, но это также не меняет цвет.

Есть ли рабочее решение для этого?

class CustomSearchBar: UISearchBar {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        self.sizeToFit()

        // Search text colour change
        let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
        textFieldInsideSearchBar?.textColor = UIColor.white

        // Search Placeholder text colour change
        let placeHolderText = textFieldInsideSearchBar!.value(forKey: "placeholderLabel") as? UILabel
        placeHolderText?.textColor = UIColor.white // doesn't work
    }
}

Ответы [ 2 ]

0 голосов
/ 29 октября 2019

Пожалуйста, добавьте это расширение и попробуйте это!

 extension UISearchBar{
        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)
            placeholderLabel.removeFromSuperview() // To remove existing label. Otherwise it will overwrite it if called multiple times.
            setValue(label, forKey: "placeholderLabel")
        }
    }

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

Использование

yourSearchBarObject.setPlaceholder(textColor: .red)
0 голосов
/ 26 октября 2019

Попробуйте это:

var searchBar: UISearchBar!
        if let textfield = searchBar.value(forKey: "searchField") as? UITextField {
            textfield.attributedPlaceholder = NSAttributedString(string: textfield.placeholder ?? "", attributes: [NSAttributedString.Key.foregroundColor : UIColor.white])
        }
...