【问题标题】:applicationWillResignActive dismiss keyboard iPhoneapplicationWillResignActive 关闭键盘 iPhone
【发布时间】:2011-11-04 02:20:35
【问题描述】:

在使用我的应用程序期间收到短信时,我希望关闭所有打开的键盘。如何从我的应用委托中的 applicationWillResignActive 执行此操作?

【问题讨论】:

    标签: objective-c ios uiapplicationdelegate


    【解决方案1】:

    answer 中的示例那样实现代码。让您的视图控制器注册UIApplicationWillResignActiveNotification。当通知触发时,请致电resignFirstResponder。这样可以避免 UIApplicationDelegate 和视图控制器之间的紧密耦合。假设您的视图控制器有一个名为 textFieldUITextField

    - (void) applicationWillResign {
        [self.textField resignFirstResponder];
    }
    
    - (void) viewDidLoad { 
        [[NSNotificationCenter defaultCenter]
            addObserver:self
            selector:@selector(applicationWillResign)
            name:UIApplicationWillResignActiveNotification 
            object:NULL];
    }
    

    【讨论】:

    • 那我怎样才能扭转applicationWillResign所做的改变呢?短信关闭后,如何重新打开键盘?
    • [self.textField becomeFirstResponder]
    • 是的,但那句话去哪儿了?
    • 我可能会把它放在视图控制器的 viewWillAppear 中。如果你愿意,你可以在你的视图控制器中为 UIApplicationDidBecomeActive 添加一个观察者,并在你的视图控制器中创建一个方法来处理通知。
    • 我没有意识到这里调用了 UIApplicationDidBecomeActive。谢谢!
    【解决方案2】:

    对于 Swift 5 实现,试试这个

    override func viewDidLoad() {
        super.viewDidLoad()
        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
    }
    
    @objc func appMovedToBackground() {
        print("App moved to background!")
    }
    
    

    更多信息请关注https://www.hackingwithswift.com/example-code/system/how-to-detect-when-your-app-moves-to-the-background

    【讨论】:

      猜你喜欢
      • 2010-09-28
      • 2011-03-21
      • 1970-01-01
      • 2013-12-09
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 2013-01-08
      相关资源
      最近更新 更多