While displaying an alert in IOS, keyboard does not resign from View

时间:2015-11-12 11:34:44

标签: ios swift keyboard alert resignfirstresponder

While displaying an alert(Wrong password) in IOS 8, keyboard opens automatically and hide the alert(just in Iphone 4s because of the screen's size), so I can't click in "OK" and I also can't dismiss keyboard because first I need to close the alert!

Keyboard hides alert

(It seems the app is recovering last keyboard's state and showing up again)

How can I close the keyboard before calling the alert?(this way the state will be "closed")

I've tried:

myTextField!.resignFirstResponder()

While calling the button, but it didn't work, the alert shows up and automatically the keyboard opens over it !

5 个答案:

答案 0 :(得分:1)

if myTextField!.resignFirstResponder() is not working properly try this when you present the alert before call this -->self.view.endEditing(true)

the above function is not work well , try

Choice -1 :Using the Responder Chain

UIApplication.sharedApplication().sendAction("resignFirstResponder", to:nil, from:nil, forEvent:nil)

This will resign the first responder (and dismiss the keyboard) every time, without you needing to send resignFirstResponder to the proper view. No matter what, this will dismiss the keyboard. It’s by far the best way to do it: no worrying about who the first responder is

Choice -2 :UIView’s endEditing

(assuming your text field is a subview of the view you call this on). Most of the time:

self.view.endEditing(true)

答案 1 :(得分:0)

set Delegate to myTextField

Include

func textFieldShouldReturn(textField: UITextField) -> Bool
    {
        textField .resignFirstResponder()
        return true
    }

Other wise Try the following

var activeField : UITextField!

    func textFieldDidBeginEditing(textField: UITextField)
    {
        activeField = textField
    }
    func textFieldDidEndEditing(textField: UITextField)
    {
        activeField = nil
    }
    func textFieldShouldReturn(textField: UITextField) -> Bool
    {
        textField .resignFirstResponder()
        return true
    }

Call activeField.resignFirstResponder() before alert appears

答案 2 :(得分:0)

I think from iOS8 you need to use UIAlertController instead of UIAlertView. Using UiAlertView in iOS8 and above is causing keyboard to popup unnecessarily. I have seen this and i made a condition to use UIAlertController for iOS8 and above. In below version UIAlertView should work fine

答案 3 :(得分:0)

这是iOS 8上的UIAlertView错误。 我有同样的问题,但UIAlertController没有问题。 :3

自iOS8以来,UIAlertView已被弃用。

https://developer.apple.com/reference/uikit/uialertview

答案 4 :(得分:0)

在Swift 4中:以下代码对我有用

    DispatchQueue.main.async() {
        self.view.endEditing(true)
    }