效果图:
实现步骤:
给textField添加一个UIToolBar,作为inputAccessoryView
private var TextFieldToolBarParamKey = "TextFieldToolBarParamKey"
extension UITextField {
var toolBar: UIToolbar? {
set(toolBar) {
objc_setAssociatedObject(self, &TextFieldToolBarParamKey, toolBar, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &TextFieldToolBarParamKey) as? UIToolbar
}
}
func showToolBar() {
setupToolBar()
self.inputAccessoryView = toolBar
}
func setupToolBar() {
toolBar = UIToolbar()
//可以让UIBarButtonItem靠右显示
let spaceItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let doneItem = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(doneItemDidClick))
toolBar?.sizeToFit()
toolBar?.items = [spaceItem, doneItem]
}
@objc func doneItemDidClick() {
self.resignFirstResponder()
}
}