Swift:textFieldShouldReturn在使用多个textFields时没有被调用

时间:2017-02-05 09:38:08

标签: ios swift uitextfield

使用多个textFieldShouldReturn时,未调用

textFieldtextFields被设置为numpads,他们应该将用户输入保存到变量textFieldEntry,但是当用户点击textFieldShouldReturn时,不会调用textField。 / p>

class TestViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var textFieldOne: UITextField!
@IBOutlet weak var textFieldTwo: UITextField!
@IBOutlet weak var textFieldThree: UITextField!
@IBOutlet weak var textFieldFour: UITextField!

var textFieldEntry: Int?

override func viewDidLoad() {
    super.viewDidLoad()
    //Looks for single or multiple taps.
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")

    // does not recognise tap when inside view
    tap.cancelsTouchesInView = false

    view.addGestureRecognizer(tap)

    self.textFieldOne.delegate = self
    self.textFieldTwo.delegate = self
    self.textFieldThree.delegate = self
    self.textFieldFour.delegate = self
}

 func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
var firstResponder = findActiveResponderFrame(view: view)

var testVar: Int?
if firstResponder!.tag == 0 {
    testVar = Int(textFieldOne.text!)
    print(testVar)
} else if firstResponder!.tag == 1 {
    testVar = Int(textFieldTwo.text!)
    print(testVar)
} else if firstResponder!.tag == 2 {
    testVar = Int(textFieldThree.text!)
    print(testVar)
} else if firstResponder!.tag == 3 {
    testVar = Int(textFieldFour.text!)
    print(testVar)

}
view.endEditing(true)
}


func findActiveResponderFrame(view:UIView)->UIView?{
    if view.isFirstResponder {
        return view
    } else {
        for sub in view.subviews {
            if let subView = sub as? UIView,
                let found = findActiveResponderFrame(view: subView){
                return found
            }
        }
    }
    return nil
}

1 个答案:

答案 0 :(得分:0)

只有在文本字段为第一响应者时用户键入返回时,才会调用should return delegate方法。您已添加了一个以编程方式结束编辑的点按手势 - 这不会调用任何委托方法。

您需要重新构建逻辑,并在调用dismissKeyboard时查找哪些文本字段是第一响应者,然后获取值。