UITapGestureRecognizer states not working

时间:2015-09-14 15:56:30

标签: ios swift uitapgesturerecognizer

Right now I have a function that shifts the whole screen up if the bottom text field is tapped otherwise if the top text field is tapped on then I don't shift the screen:

func keyboardWillShow(notification: NSNotification) {
        var tapTopTextField: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: nil)
        topTextField.addGestureRecognizer(tapTopTextField)
        topTextField.userInteractionEnabled = true
        if(tapTopTextField.state == .Began) {
            // don't move screen
        }
        // then it is the bottomTextField that is tapped
        else {
            self.view.frame.origin.y -= getKeyboardHeight(notification)
        }

    }

So with this code my screen still shifts if the topTextField is tapped and the other way to make it not change is by letting the state be .Possible but doing this disables the screen moving up when the bottomTextField is tapped. Is there something that I am missing here, and also is there a more elegant way of doing this?

Update: So I realised that the reason this is happening is because when this function is called the textField has already been selected and hence is reset to the .Possible state

2 个答案:

答案 0 :(得分:0)

The way I go is design the UI so that the text fields are at the top out of the way of the keyboard. If something needs to be at the bottom and could be covered by the keyboard I let the user deal with scrolling.

答案 1 :(得分:0)

所以我想出了答案,就在这里!

func keyboardWillShow(notification: NSNotification) {

            if(topTextField.isFirstResponder()) {
                // don't move screen
            }
            // then it is the bottomTextField that is tapped
            else {
                self.view.frame.origin.y -= getKeyboardHeight(notification)
            }

        }

通过使用isFirstResponder,我可以检查textField是否被选中!