iOS 13 Set UISearchTextField placeholder color

后端 未结 5 1717
执笔经年
执笔经年 2020-12-10 02:20

How do you set the placeholder color of iOS 13\'s UISearchTextField?

I tried the following with no success:

searchField.attributedPlaceh         


        
5条回答
  •  情深已故
    2020-12-10 02:46

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

    Copy of my answer from here

提交回复
热议问题