方法1:
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).title = "取消"
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.white], for: .normal)
方法2:(你需要知道取消按钮的Value值)
let cancelButton = searchBar.value(forKey: "cancelButton") as! UIButton
cancelButton.setTitle("取消", for: .normal)
cancelButton.setTitleColor(UIColor.black, for: .normal)
不修改代码,让Cancel按钮显示中文:
在Info.plist文件中修改Localization native development region,默认为en,设置为China
因为在SearchController中的searchBar加载速度比较慢,所以需要延迟让他成为第一响应者
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.perform(#selector(ReportViewController.showKeyboard), with: nil, afterDelay: 0.02)
}
func showKeyboard() {
self.mySearchController.searchBar.becomeFirstResponder()
}
修改SearchBar颜色
// 修改颜色
func setImageColor(_ color: UIColor, _ size:CGSize) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
searchBar.backgroundImage = setImageColor(UIColor.clear, searchBar.bounds.size)
searchBar.backgroundColor = UIColor.yourColor