ios - self.tabBarController 有时为零

标签 ios swift swift3 uikit uitabbarcontroller

我有 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/

相关文章:

ios - 使用触摸移动 SceneKit 中的节点

swift - 检查结构中的任何属性是否为 nil - Swift 4

sdk - 线程 1 : signal SIGABRT

ios - 将 NSDate 插入 CoreData 时出错

iOS:处理 App Delegate 中的无效 session

ios - 在 iOS 中访问最近使用的表情符号列表

swift - 更新到 Swift 3 后奇怪的转义函数行为

swift - 知道用户是否更新应用程序或是否有新购买(swift 3)

ios - 自定义 UITableViewCell 图像上的圆角

ios - 首次在iOS设备上安装enterprise in house distribution App失败