self.tabBarController有时为零

时间:2017-06-07 10:05:59

标签: ios swift swift3 uikit uitabbarcontroller

我有UIViewController第一个),底部有标签栏。我在这个控制器中有下一个代码:

let tabBarHeight = self.tabBarController?.tabBar.frame.size.height

它运行正常,但当我从第一个转到下一个(第二个)控制器,然后按下Back按钮并返回< em> first ,self.tabBarController为零。为什么会这样?我只有一个版本,那堆控制器过于拥挤。

我该如何解决这个问题?我需要此高度来计算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:

我可以看到tab bar。但它是nil

结构(Show个segues):tabbar -> navbar -> viewcontroller -> viewcontroller -> viewcontroller (first) -> viewcontroller (second)

谢谢

2 个答案:

答案 0 :(得分:1)

将TabBar控制器设置为根,然后将导航控制器设置为tabBar的项目之一,将TestViewController设置为该导航控制器的根。然后这个TestViewController有一个文本字段来检查keyboardWillShow函数和点击UIButton - &#34;按钮&#34;新的viewcontroller被推了。点击后再次检查keyboardWillShow函数self.tabBarController不是零,我在该函数中获得正确的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)")

            })
        }
    }

}

答案 1 :(得分:0)

在iOS&gt; = 8.0上,标签栏高度始终为49磅(请参阅What's the height of a UITabBar on iOS 8, iOS 9 and iOS 10?)。

如果在无法访问tabbar时需要一些复杂的UI用例来解决,只需将该数字放入常量并使用它,例如:

let tabbarHeight: CGFloat = 49.0

或,将值保存到变量,例如

var tabbarHeight:

viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated: animated)

    self.tabbarHeight = self.tabBarController!.tabBar.frame.size.height
}