有谁知道如何更改搜索栏的输入键盘类型?代码
searchController.searchBar.inputView = input
不像文本字段那样工作。我已经读过searchBar的子视图是一个文本字段,但我不知道如何访问该子视图来更改inputView。
答案 0 :(得分:1)
我认为你想要显示不同于标准的键盘, 确保您已将委托分配给键盘。
class ViewController: UIViewController, UISearchBarDelegate, KeyboardDelegate
{
@IBOutlet weak var searchBar: UISearchBar!
override func viewDidLoad() {
let keyboardView = KeyboardView(frame: CGRect(x: 0, y: 0, width: 375, height: 165))
keyboardView.delegate = self
let searchTextField = searchBar.value(forKey: "_searchField") as! UITextField
searchTextField.inputView = keyboardView
}
func keyWasTapped(text: String) {
searchBar.text = text
}
}
我的自定义键盘类
protocol KeyboardDelegate: class {
func keyWasTapped(text: String)
}
class KeyboardView: UIView {
// This variable will be set as the view controller so that
// the keyboard can send messages to the view controller.
weak var delegate: KeyboardDelegate?
// MARK:- keyboard initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeSubviews()
}
override init(frame: CGRect) {
super.init(frame: frame)
initializeSubviews()
}
func initializeSubviews() {
let xibFileName = "KeyboardView" // xib extention not included
let view = Bundle.main.loadNibNamed(xibFileName, owner: self, options: nil)?[0] as! UIView
self.addSubview(view)
view.frame = self.bounds
}
// MARK:- Button actions from .xib file
@IBAction func keyTapped(_ sender: UIButton) {
// When a button is tapped, send that information to the
// delegate (ie, the view controller)
self.delegate?.keyWasTapped(text: sender.titleLabel!.text!) // could alternatively send a tag value
}
}
答案 1 :(得分:0)
你必须这样访问:
if let searchBarTxtField = searchController.searchBar.valueForKey("_searchField") as UITextField {
searchBarTxtField.inputView = input
}