我有以下代码:

func navbarbutton() {
    UIView.animateWithDuration(0.2, animations: { () -> Void in
        let current = self.navigationController?.navigationBar.frame
        self.navigationController?.navigationBar.frame = CGRectMake(self.frame!.origin.x, self.frame!.origin.y, self.frame!.size.width, current!.size.height + 50)
        self.navigationController?.navigationBar.layoutIfNeeded()
    })
}

我可以将导航栏的高度增加50 dp。这对我来说不是问题。我遇到的问题是UIBarButtonItems都与底部对齐。如何使它们与顶部对齐,以便自己在底部添加更多内容?我根据图片得到一些东西:

ios - 增加导航栏高度-LMLPHP

是否可以使其与顶部对齐?

最佳答案

试试这个代码:

注意:代码已在Swift 3中测试。

答案1: 更新了答案

class ViewController: UIViewController {

var customBar: UINavigationBar = UINavigationBar()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    //Title
    title = "Some Title"

    // Add bar button item
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action:  #selector(addTapped))
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(addTapped))

    self.customBar.frame = CGRect(x:0, y:0, width:view.frame.width, height:(navigationController?.navigationBar.frame.height)! + 50)
    self.customBar.backgroundColor = UIColor.green
    self.view.addSubview(customBar)
}

func addTapped() {

    print("Button Pressed")

}

输出:

ios - 增加导航栏高度-LMLPHP

答案2:
override var isViewLoaded: Bool {

    // Add bar button item
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action:  #selector(addTapped))
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(addTapped))

    //Vertical and Horizonal barButtonItem position offset
    navigationItem.leftBarButtonItem?.setTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: 20), for: UIBarMetrics.default)

    navigationItem.rightBarButtonItem?.setTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: 20), for: UIBarMetrics.default)

    return true
}

func addTapped() {

    print("Button Pressed")

}

注意:上面的代码仅适用于 isViewLoaded:布尔方法。但是,不走运。何时,我在其他viewLoad方法中尝试了此代码。

输出1: barButtonItem垂直向上移动了20个像素。

ios - 增加导航栏高度-LMLPHP

输出2: barButtonItem垂直向下移动20个像素。

ios - 增加导航栏高度-LMLPHP

希望以上代码能解决您的问题。

10-07 20:28