UISearchBar change placeholder color

前端 未结 17 2417
南旧
南旧 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:57

    iOS 13

    Use a custom search bar.

    This also works when part of a UISearchController inside a UINavigationItem (with hidesSearchBarWhenScrolling = true).

    We want to apply our changes immediately after UIAppearance proxies are being applied since those are the most likely root cause:

    class MySearchBar : UISearchBar {
        // Appearance proxies are applied when a view is added to a view hierarchy, so apply your tweaks after that:
        override func didMoveToSuperview() {
            super.didMoveToSuperview() // important! - system colors will not apply correctly on ios 11-12 without this
    
            let placeholderColor = UIColor.white.withAlphaComponent(0.75)
            let placeholderAttributes = [NSAttributedString.Key.foregroundColor : placeholderColor]
            let attributedPlaceholder = NSAttributedString(string: "My custom placeholder", attributes: placeholderAttributes)
            self.searchTextField.attributedPlaceholder = attributedPlaceholder
            
            // Make the magnifying glass the same color
            (self.searchTextField.leftView as? UIImageView)?.tintColor = placeholderColor
        }
    }
    
    // Override `searchBar` as per the documentation
    private class MySearchController : UISearchController {
        private lazy var customSearchBar = MySearchBar()
        override var searchBar: UISearchBar { customSearchBar }
    }
    

    That took quite some time to get working properly...

提交回复
热议问题