Как настроить изменение цвета заполнителя на панели поиска? - PullRequest
0 голосов
/ 27 января 2019
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: [NSAttributedString.Key.foregroundColor:color])
    }
}

func setPlaceholderfont(fontfamily: UIFont) {

    if let textField = getSearchBarTextField() {
        textField.attributedPlaceholder = NSAttributedString(string: self.placeholder != nil ? self.placeholder! : "", attributes: [NSAttributedString.Key.font:fontfamily])
    }
}


 }

Я создал расширение для Uisearchbbar, чтобы иметь возможность настроить заполнитель

В расширении setPlaceholderfont () работает нормально

, когда явызовите метод ниже, цвет текста заполнителя не меняется

pick.searchBar.setPlaceholderTextColor(color: Server().primarycolor)

1 Ответ

0 голосов
/ 27 января 2019

Когда вы вызываете два метода для обновления цвета и шрифта атрибутивных заполнителей, вы перезаписываете один последним.Итак, если вы устанавливаете цвет первым, а шрифт вторым, атрибут цвета удаляется при установке атрибута шрифта.

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

extension UITextField {
    var placeholderColor: UIColor? {
        get { return placeholderAttributes?[.foregroundColor] as? UIColor }
        set { placeholderAttributes?[.foregroundColor] = newValue }
    }

    var placeholderFont: UIFont? {
        get { return placeholderAttributes?[.font] as? UIFont }
        set { placeholderAttributes?[.font] = newValue }
    }

    var placeholderAttributes: [NSAttributedString.Key: Any]? {
        get { return attributedPlaceholder?.attributes(at: 0, effectiveRange: nil) }
        set { attributedPlaceholder = .init(string: placeholder ?? "", attributes: newValue) }
    }
}

Так что сократите ваше расширение UISearchBar (я бы заменил getSearchBarTextField метод с вычисляемым свойством textField), мы можем удалить любую ссылку на приписанные строки и т. Д.

var textField: UITextField? {
    return getViewElement(type: UITextField.self)
}

func setTextColor(color: UIColor) {
    textField?.textColor = color
}

func setPlaceholderTextColor(color: UIColor) {
    textField?.placeholderColor = color
}

func setPlaceholderFont(font: UIFont) {
    textField?.placeholderFont = font
}

Хотя свойства с соответствующими типами (UIColor, UIFont) могутВ некоторых ситуациях это может пригодиться, вам технически не нужны свойства placeholderColor и placeholderFont, поскольку вы можете просто установить их, используя свойство текстового поля placeholderAttributes из расширения.

extension UITextField {
    var placeholderAttributes: [NSAttributedString.Key: Any]? {
        get { return attributedPlaceholder?.attributes(at: 0, effectiveRange: nil) }
        set { attributedPlaceholder = .init(string: placeholder ?? "", attributes: newValue) }
    }
}

extension UISearchBar {

    // ...

    func setPlaceholderTextColor(color: UIColor) {
        textField?.placeholderAttributes?[.foregroundColor] = color
    }

    func setPlaceholderfont(fontfamily: UIFont) {
        textField?.placeholderAttributes?[.font] = fontfamily
    }
}
...