如何以编程方式在iOS中获得较高的导航栏

sri*_*ran 5 xcode objective-c uinavigationbar ios swift

keyboardwillshown当键盘隐藏时,我必须将视图向上移动到正常位置

实际上,我在viewdidload方法上使用了以下代码:

override func viewDidLoad() { 

    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) 

}
Run Code Online (Sandbox Code Playgroud)

这是我用来上下移动的方法

func keyboardWillShow(notification:NSNotification){ 

    print("keyboardwillshow")
    let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()

    self.view.frame = CGRectMake(0.0, -keyboardSize!.size.height + (self.navigationController?.navigationBar.frame.size.height)! + 20 , self.view.frame.size.width, self.view.frame.size.height )  

}

func keyboardWillHide(notification:NSNotification){

    self.view.frame = CGRectMake(0.0,(self.navigationController?.navigationBar.frame.size.height)!, self.view.frame.size.width, self.view.frame.size.height)
//  self.view.frame.origin.y += 350

}
Run Code Online (Sandbox Code Playgroud)

当我运行该程序时,它将显示一个运行时错误,

意外发现展开时发现零

请帮我解决这个问题。

Kru*_*nal 5

使用iPhone-X,顶部栏(导航栏+状态栏)的高度被更改(增加)。

如果您想要顶部栏(导航栏+状态栏)的确切高度,请尝试以下操作:

目标C

CGFloat topbarHeight = ([UIApplication sharedApplication].statusBarFrame.size.height +
       (self.navigationController.navigationBar.frame.size.height ?: 0.0));
Run Code Online (Sandbox Code Playgroud)

斯威夫特4

let topBarHeight = UIApplication.shared.statusBarFrame.size.height +
        (self.navigationController?.navigationBar.frame.height ?? 0.0)
Run Code Online (Sandbox Code Playgroud)

为方便起见,请尝试使用此UIViewController扩展

extension UIViewController {

    /**
     *  Height of status bar + navigation bar (if navigation bar exist)
     */

    var topbarHeight: CGFloat {
        return UIApplication.shared.statusBarFrame.size.height +
            (self.navigationController?.navigationBar.frame.height ?? 0.0)
    }
}
Run Code Online (Sandbox Code Playgroud)

迅捷3

let topBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height +
(self.navigationController?.navigationBar.frame.height ?? 0.0)
Run Code Online (Sandbox Code Playgroud)


Sou*_*rma 0

let navigationBarHeight = self.navigationController?.navigationBar.frame.height ?? 0
Run Code Online (Sandbox Code Playgroud)

  • 我的做法略有不同:`let navigationBarHeight = self.navigationController?.navigationBar.frame.height ?? 0` (3认同)