首先,完成按钮代码如下
class ViewController: UIViewController, UITextFieldDelegate {
let inputNumber = UITextField(frame: CGRect(x: 150.0, y: 100.0, width: 200.0, height: 50.0))
let toolBarKeyBoard = UIToolbar()
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
var result : String!
override func viewDidLoad() {
super.viewDidLoad()
calculatePrice()
}
func calculatePrice () {
priceInputLabel.keyboardType = .numberPad
priceInputLabel.clearButtonMode = .whileEditing
self.view.addSubview(priceInputLabel)
toolBarKeyBoard.sizeToFit()
toolBarKeyBoard.setItems([flexibleSpace, doneButton], animated: false)
priceInputLabel.inputAccessoryView = toolBarKeyBoard
}
@objc func donePressed() {
view.endEditing(true)
}
}
它运作正常。当我触摸'inputNumber(UITextField)'时,会弹出一个键盘。当我输入数字并触摸“完成”按钮时,键盘会自动解除。好。
但是,在其他代码中,低于,不起作用。
class FruitTableViewCell: UITableViewCell, UITextFieldDelegate {
var fruitsTextField = UITextField()
let toolBarKeyBoard = UIToolbar()
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePressed))
var result : String!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(fruitsTextField)
}
override func layoutSubviews() {
super.layoutSubviews()
fruitsTextField.frame = CGRect(x: 250, y: 7.5, width: 100, height: 30)
fruitsTextField.textColor = UIColor(red: CGFloat(242/255.0), green: CGFloat(56/255.0), blue: CGFloat(90/255.0), alpha: 1.0)
fruitsTextField.keyboardType = .numberPad
fruitsTextField.clearButtonMode = .whileEditing
toolBarKeyBoard.sizeToFit()
fruitsTextField.inputAccessoryView = toolBarKeyBoard
toolBarKeyBoard.setItems([flexibleSpace, doneButton], animated: false)
}
@objc func donePressed() {
fruitTextField.endEditing(true)
}
我可以构建,我可以切换键盘,我可以触摸完成按钮,但它不会解雇键盘。我认为,底线的函数'@objc func donePressed()'很重要。
第一个代码是'view.endEditing(true)'但这些是'fruitTextField.endEditing(true)'
所以,我试图改变代码。
@objc func donePressed() {
contentView.endEditing(true)
}
但是不起作用。
问题1。我该怎么解雇键盘?
问题2。为什么即使我触摸“完成”按钮,键盘也不会消失?
问题3。在第二个代码中,键盘不是FirstResponder?
问题4。在第二个代码中,'。endEditing'的视图是什么?
谢谢!
将“完成按钮”初始化更改为:
lazy var doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(donePressed))
你需要target: self
,你需要它是lazy
,以便在实例化按钮时self
有效。
您还可以将已完成的func更改为:
@objc func donePressed() {
fruitsTextField.resignFirstResponder()
}
并没有真正改变功能,但我相信这是推荐的方法。