xhr Asked:2020-12-13 17:00:59 +0000 UTC2020-12-13 17:00:59 +0000 UTC 2020-12-13 17:00:59 +0000 UTC 如何更改 UISearchController 中搜索文本字段的背景颜色? 772 如何更改 UISearchController 中搜索文本字段的默认灰色背景颜色? swift 2 个回答 Voted Best Answer xhr 2020-12-16T17:34:18Z2020-12-16T17:34:18Z 更改 UISeachController 中文本字段背景颜色的代码示例: class ViewController: UIViewController { let searchController = UISearchController(searchResultsController: nil) private lazy var searchTextField: UITextField? = { [unowned self] in var textField: UITextField? searchController.searchBar.subviews.forEach({ view in view.subviews.forEach({ view in if let view = view as? UITextField { textField = view } }) }) return textField }() override func viewDidLoad() { super.viewDidLoad() searchController.obscuresBackgroundDuringPresentation = false searchController.searchBar.placeholder = "Search Candies" navigationItem.searchController = searchController definesPresentationContext = true if let bg = self.searchTextField?.subviews.first { bg.backgroundColor = .green bg.layer.cornerRadius = 10 bg.clipsToBounds = true } } } 结果: Vitaly Potlov 2020-12-14T04:34:32Z2020-12-14T04:34:32Z 尝试这样的自定义UISearchBar: func configureSearchBar() { searchBar.layer.borderWidth = 0 searchBar.backgroundColor = UIColor.white searchBar.backgroundImage = UIImage() searchBar.barTintColor = UIColor.white if let textField = self.searchBar.value(forKey: "searchField") as? UITextField { textField.font = UIFont.systemFont(ofSize: 23, weight: UIFont.Weight.light) textField.textColor = UIColor(withHex: 0x000000) textField.borderStyle = .none textField.leftViewMode = .never textField.textAlignment = .left if let clearButton = textField.value(forKey: "clearButton") as? UIButton { clearButton.setImage(UIImage(named: "searchClearIco")!, for: .normal) clearButton.setImage(UIImage(named: "searchClearIcoTap")!, for: .highlighted) } } }
更改 UISeachController 中文本字段背景颜色的代码示例:
结果:
尝试这样的自定义
UISearchBar: