我有文字视图,我希望能够有一个完成按钮。我添加了一个UI工具栏,并将其作为插座连接,并将IB操作连接到完成按钮
工具栏没有显示?我错过了什么?
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
ingredientsTextField.inputAccessoryView
= keyboardToolbar
return true
}
@IBAction func didClickDoneButton(_ sender: UIBarButtonItem) {
ingredientsTextField.endEditing(true)
}
答案 0 :(得分:0)
可能是您创建的工具栏错误,请检查此
func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
self.addAccessoryView()
return true
}
func addAccessoryView() -> Void {
let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 44))
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonTapped(button:)))
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolBar.items = [flexibleSpace,doneButton]
toolBar.tintColor = UIColor.red
self.textView.inputAccessoryView = toolBar
}
func doneButtonTapped(button:UIBarButtonItem) -> Void {
// do you stuff with done here
}
答案 1 :(得分:0)
您的代码段看起来很好!您是否为textfield
设置了代理?如果您错过了,请将其设置为func textFieldShouldBeginEditing
将不会被调用!
请参阅以下工作代码供您参考,
import UIKit
class ViewController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
internal func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
let numberToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 50))
numberToolbar.barStyle = UIBarStyle.default
numberToolbar.items = [
UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: Selector(("cancelNumberPad"))),
UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil),
UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: Selector(("doneWithNumberPad")))]
numberToolbar.sizeToFit()
textField.inputAccessoryView
= numberToolbar
return true
}
@IBAction func didClickDoneButton(_ sender: UIBarButtonItem) {
textField.endEditing(true)
}
@IBAction func buttonClick(_ sender: Any) {
textField.endEditing(true)
}
}