How to add a 1 pixel gray border around a UISearchBar TextField

后端 未结 6 2407
攒了一身酷
攒了一身酷 2021-02-19 14:21

I\'m trying to figure out how to add a 1 pixel stroke gray border to my UISearchBar in my app. The Facebook Messenger app accomplishes this quite well. (see pic below).

6条回答
  •  悲哀的现实
    2021-02-19 14:49

    I upvoted Yaroslav's answer but it's broken as of iOS 13. Here is what works today:

        func changeSearchBarAppearance() {
            var searchTextField : UITextField?
            if #available(iOS 13, *) {
                // brand new searchTextField is available as of iOS 13
                searchTextField = searchBar.searchTextField
            } else {
                // Yaroslav's answer still works in iOS versions less than 13
                // here's a slightly different implementation:
                if let matchingTextField = searchBar.subviews[0].subviews.compactMap ({ $0 as? UITextField }).first {
                    searchTextField = matchingTextField
                }
            }
    
            guard let validTextField = searchTextField else {
                return
            }
    
            validTextField.layer.cornerRadius = 16
            validTextField.layer.borderWidth = 1.0
            validTextField.layer.borderColor = UIColor.grey.cgColor
            validTextField.backgroundColor = .white
            validTextField.placeholder = "insert-some-placeholder-text"
        }
    

提交回复
热议问题