我是 Swift 的新手,当 textField 在自定义 tableview 单元格上时,我一直在努力隐藏键盘。我认为问题源于 TableViewCell 类中的 textField 引用,但我不能确定。我什么都试过了,有点迷路了。
我的代码包括:
表格 View 单元格:
import UIKit
class TableViewCell: UITableViewCell, UITextFieldDelegate
{
@IBOutlet weak var userText: UITextField!
@IBAction func answers(_ sender: UITextField)
{
}
override func setSelected(_ selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.delegate = self
textField.resignFirstResponder()
return true
}
}
和 TableViewController:
import UIKit
class TableViewController: UITableViewController, UITextFieldDelegate
{
var textfield = TableViewCell()
override func viewDidLoad()
{
super.viewDidLoad()
let myText = textfield.userText
textField.resignFirstResponder()
myText?.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
return cell
}
}
我尝试从两个类运行 textFieldShouldReturn
函数,但我无法让它工作。
最佳答案
从 UITableViewCell
中删除 UITextFieldDelegate
和委托(delegate) func
然后在UITableViewController
->里面
`override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)as! TableViewCell
cell.userText.delegate = self
return cell
}
然后你想在 UITableViewController
中添加 textFieldShouldReturn
并返回 true 试试这个
关于ios - 使用自定义 uitableViewCell 在 tableView 上按下回车键或单击时隐藏键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44251668/