方法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矩肩,默認(rèn)為en,設(shè)置為China
因?yàn)樵赟earchController中的searchBar加載速度比較慢仰剿,所以需要延遲讓他成為第一響應(yīng)者
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