import UIKit
class ViewController: UIViewController {
// your `UITextfield` instance
// Don't forget to attach it from the IB or create it programmaticly
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Assign the delegate to self
textField.delegate = self
}
}
// MARK: Create extension to conform to UITextfieldDelegate
extension ViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
setupTextFieldsAccessoryView()
return true
}
func setupTextFieldsAccessoryView() {
guard textField.inputAccessoryView == nil else {
print("textfields accessory view already set up")
return
}
// Create toolBar
let toolBar: UIToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 44))
toolBar.barStyle = UIBarStyle.black
toolBar.isTranslucent = false
// Add buttons as `UIBarButtonItem` to toolbar
// First add some space to the left hand side, so your button is not on the edge of the screen
let flexsibleSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) // flexible space to add left end side
// Create your first visible button
let doneButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(didPressDoneButton))
// Note, that we declared the `didPressDoneButton` to be called, when Done button has been pressed
toolBar.items = [flexsibleSpace, doneButton]
// Assing toolbar as inputAccessoryView
textField.inputAccessoryView = toolBar
}
func didPressDoneButton(button: UIButton) {
// Button has been pressed
// Process the containment of the textfield or whatever
// Hide keyboard
textField.resignFirstResponder()
}
}
5条答案
按热度按时间jjhzyzn01#
第一个问题,你可以把
textField
的inputAccessoryView
设置为你的自定义视图,这样可以自定义键盘的表头。结果是:
你可以像下面这样做;
首先,您应该示例化要添加到键盘上方的视图。
在你的
CustomAccessoryView
中,你可以设置按钮的动作:8tntrjer2#
我建议为您的
UITextField
的accessoryView属性创建一个toolbar
。我们的想法是在第一次显示文本字段之前添加一次
toolbar
,因此,我们将delegate
赋值给self,并使用我们的实现覆盖textFieldShouldBeginEditing
委托调用以添加accessoryView
。下面是一个简单的例子,如何实现它:
您的输出应该是:
klsxnrf13#
您必须使用文本字段的inputAccessoryView。
你可以把下面的代码片段放到你的viewDidLoad()中:
js81xvg64#
只需复制并粘贴简单代码,即可使用嵌入键盘的配件按钮
zqdjd7g95#
要添加一个带有“完成”按钮的工具栏,该按钮可关闭UITextField上方的键盘,您可以使用以下函数编写一个UITextField扩展:
然后可以在文本字段中调用该函数,如下所示: