UISearchBar change placeholder color

前端 未结 17 2445
南旧
南旧 2020-12-04 15:16

Has anyone any idea or code sample on how can I change the text color of the placeholder text of a UISearchBar?

17条回答
  •  感动是毒
    2020-12-04 15:50

    It looks like Apple does not want us to play with the placeholder colors when it comes to UISearchBar class. So, let's create our own placeholder label!

    • No subclassing.
    • Works with iOS 13 SDK.
    • Just one innocent workaround.

    let searchBar = searchController.searchBar
    // ...
    // Configure `searchBar` if needed
    // ...
    
    let searchTextField: UITextField
    if #available(iOS 13, *) {
        searchTextField = searchBar.searchTextField
    } else {
        searchTextField = (searchBar.value(forKey: "searchField") as? UITextField) ?? UITextField()
    }
    
    // Since iOS 13 SDK, there is no accessor to get the placeholder label.
    // This is the only workaround that might cause issued during the review.
    if let systemPlaceholderLabel = searchTextField.value(forKey: "placeholderLabel") as? UILabel {
        // Empty or `nil` strings cause placeholder label to be hidden by the search bar
        searchBar.placeholder = " "
    
        // Create our own placeholder label
        let placeholderLabel = UILabel(frame: .zero)
    
        placeholderLabel.text = "Search"
        placeholderLabel.font = UIFont.systemFont(ofSize: 17.0, weight: .regular)
        placeholderLabel.textColor = UIColor.blue.withAlphaComponent(0.5)
    
        systemPlaceholderLabel.addSubview(placeholderLabel)
    
        // Layout label to be a "new" placeholder
        placeholderLabel.leadingAnchor.constraint(equalTo: systemPlaceholderLabel.leadingAnchor).isActive = true
        placeholderLabel.topAnchor.constraint(equalTo: systemPlaceholderLabel.topAnchor).isActive = true
        placeholderLabel.bottomAnchor.constraint(equalTo: systemPlaceholderLabel.bottomAnchor).isActive = true
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        placeholderLabel.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)
    } else {
        searchBar.placeholder = ""
    }
    

提交回复
热议问题