【发布时间】:2019-02-18 06:43:59
【问题描述】:
首先,完成按钮代码如下
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' 的视图是什么?
谢谢!
【问题讨论】:
-
在 donePressed() 中使用
resignFirstResponder()而不是 endEditing -
我将 'contentView.endEditing(true)' 更改为 'fruitTextField.resignFirstResponder()' 但不起作用。 'contentView.resignFirstResponder()' 也没有。
标签: swift xcode uitableview keyboard