我们使用搜索栏(UISearchBar)时,如果将其设置为“Shows Cancel Button”后,输入框右侧会有个取消按钮(标题文字是Cancel)。
有时我们想要将这个按钮修改成其他文字,比如“搜索”。虽然 searchBar 不提供直接修改这个按钮文字的方法或属性,但我们可以换种方式来实现。
1,修改searchBar取消按钮的文字
先获取到 searchBar 中的取消按钮,再设置这个按钮的 title 即可。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
let uiButton = searchBar.valueForKey("cancelButton") as! UIButton
uiButton.setTitle("搜索", forState: UIControlState.Normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
2,修改searchBar取消按钮的文字颜色
同样先获取到 searchBar 中的取消按钮,再设置这个按钮的 titleColor 即可。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
let uiButton = searchBar.valueForKey("cancelButton") as! UIButton
uiButton.setTitle("搜索", forState: UIControlState.Normal)
uiButton.setTitleColor(UIColor.orangeColor(),forState: .Normal)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}