【问题标题】:UIKeyboardWillShowNotification and UIAlertKeyboardWillShowNotification 和 UIAlert
【发布时间】:2016-05-24 19:04:20
【问题描述】:

我正在使用 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 按钮时,滚动视图中断。

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

【问题讨论】:

  • 在键盘完全关闭后尝试调用displayAlert() 函数。

标签: ios iphone swift uiscrollview uialertview


【解决方案1】:

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

【讨论】:

  • 感谢 Nermin,您的回答帮助我了解了这一点。答案实际上是非常愚蠢的。正如您指出的那样,通知并不可靠。正如您所指出的,有时他们会被多次调用。为了防止这种情况,我放了一个keyboardVisible bool 来更有效地监控它。我愚蠢地忘记将'if keyboardVisible == true{...} 添加到keyboardWillHide。问题解决了!
猜你喜欢
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 2013-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多