UIKeyboardWillShowNotification和UIAlert

时间:2016-05-24 19:04:21

标签: ios iphone swift uiscrollview uialertview

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

这是我使用的代码:

    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)
}

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

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

1 个答案:

答案 0 :(得分:0)

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

相关问题