KeyboardWillShowNotification 和 UIAlert

UIKeyboardWillShowNotification and UIAlert

我正在使用 UIKeyboardWillShowNotification 在调用键盘时上下滚动视图。这在大多数情况下工作正常。但是,键盘有一个可以产生 UIAlert 的完成按钮。没有 UIAlert 就没有问题,但是如果 UIAlert 被调用,scrollview 会发生一些奇怪的事情,它似乎停止工作,因为它的大小变小了。

这是我正在使用的代码:

    func adjustInsetForKeyboardShow(show: Bool, notification: NSNotification) {
    guard let value = notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue else { return }
    let keyboardFrame = value.CGRectValue()
    let adjustmentHeight = (CGRectGetHeight(keyboardFrame) + 70) * (show ? 1 : -1)


    scrollView.contentInset.bottom += adjustmentHeight
    //scrollView.scrollIndicatorInsets.bottom += adjustmentHeight
}

func keyboardWillShow(notification: NSNotification) {
    if keyboardVisible == false {
    adjustInsetForKeyboardShow(true, notification: notification)
    keyboardVisible = true
    }
}

func keyboardWillHide(notification: NSNotification) {
    adjustInsetForKeyboardShow(false, notification: notification)
    keyboardVisible = false
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

键盘上有一个按钮,代码如下:

func displayAlert(title:String, message:String, view:UIViewController){
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action) -> Void in
    }))
    view.presentViewController(alert, animated: true, completion: nil)
}

结果是发出警报,然后当我按下“确定”按钮时,滚动视图中断。

有人可以帮忙吗?如果您需要更多代码,请告诉我

我首先建议您尽可能使用 table 视图而不是滚动视图。其次,我不知道你是否测试过,但这些通知被调用了不止一次,有时它们的行为并不像你预期的那样。我还没有尝试过,但我假设一旦你显示 UIAlert 这些方法之一就会被触发,然后你的内容大小就会变得疯狂。尝试设置断点,看看会发生什么。此外,尝试在 return 上关闭键盘,然后调用 displayAlert()。另外,从经验来看,当您离开屏幕时,不会调用这种删除观察者的 deinit 方法,我不知道您是否有理由使用它,或者?最好使用 viewWillAppear、viewWillDissapear 方法。