我有 UIViewController
(第一个),底部有标签栏。我在这个 Controller 中有下一个代码:
let tabBarHeight = self.tabBarController?.tabBar.frame.size.height
它工作正常,但是当我从这个第一个转到下一个(第二个) Controller ,然后按返回
按钮和返回首先,self.tabBarController
为nil。为什么会这样?我只有一个版本,那堆 Controller 太拥挤了。
我该如何解决这个问题?我需要这个高度来计算 keyboardWillShow
函数中约束变化的一些值。
更新:
如何调用它:
// MARK: - Scroll view on keyboard show/hide
extension CommentariesController: UITextFieldDelegate {
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
let tabBarHeight = self.tabBarController?.tabBar.frame.size.height
UIView.animate(withDuration: 1.0, animations: {
self.newCommentViewBotConstraint.constant = -keyboardHeight + tabBarHeight!
self.view.layoutIfNeeded()
})
}
}
// other code
}
更新 2:
我可以看到标签栏
。但它是 nil
。
结构(使用 Show
segues):tabbar -> navbar -> viewcontroller -> viewcontroller -> viewcontroller (first) -> viewcontroller (second)
.
谢谢
最佳答案
TabBar Controller 设置为根,然后将导航 Controller 设置为 tabBar 的项目之一,并将 TestViewController 设置为该导航 Controller 的根。然后这个 TestViewController 有一个文本字段来检查 keyboardWillShow 函数,并在点击 UIButton - “按钮”时按下新的 viewcontroller。反复点击检查 keyboardWillShow
函数 self.tabBarController
不是 nil 并且我在该函数中得到了正确的 tabBar 高度
NotificationCenter.default.addObserver(self, selector: #selector(TestViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
extension TestViewController {
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardHeight = keyboardSize.height
let tabBarHeight = self.tabBarController?.tabBar.frame.size.height
UIView.animate(withDuration: 1.0, animations: {
print("tabBarheight - \(tabBarHeight)")
})
}
}
}
关于ios - self.tabBarController 有时为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44409602/