UITextfield在UITableViewCells中 - 关闭键盘

Net*_*zer 1 uitextfield ios uitextfielddelegate swift

UITextfields在每个表格单元格中都有几个.通过点击"完成"按钮或触摸键盘外部,键盘应该被解除.

我的问题:textFieldShouldEndEditing只有当我点击另一个文本字段并且键盘不会被解除时才调用该方法.我想我已经实现了必要的部分(委托和协议方法).

有谁知道我在这里失踪了....?

这是代码(相关部分):

class myVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate  {...
Run Code Online (Sandbox Code Playgroud)

这是细胞设置......

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let tcell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "tbCell")

    let textfield: UITextField = UITextField(frame:...

    switch (indexPath.section) {
    case 0: ...
    case 1: 
            textfield.text = section2[indexPath.row]
            tcell.addSubview(textfield)
            textfield.delegate = self
            return tcell
Run Code Online (Sandbox Code Playgroud)

这个协议方法:

func textFieldShouldEndEditing(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        print("method is called")
        return true
    }
Run Code Online (Sandbox Code Playgroud)

谢谢!

小智 6

我在Objective-C中给出了这个答案,因为我不使用Swift

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
Run Code Online (Sandbox Code Playgroud)

当你滚动你的桌面视图,并且:

tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
Run Code Online (Sandbox Code Playgroud)

当你在文本区域外触摸时.


Abh*_*ain 5

斯威夫特 4.0

tableView.keyboardDismissMode = .onDrag
Run Code Online (Sandbox Code Playgroud)

或者

tableView.keyboardDismissMode = .interactive
Run Code Online (Sandbox Code Playgroud)