一尘不染

增加NavigationBar的高度

swift

我有以下代码:

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是都与底部对齐。如何使它们与顶部对齐,以便自己添加更多内容?我根据图片得到一些东西:

在此处输入图片说明

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


阅读 277

收藏
2020-07-07

共1个答案

一尘不染

试试这个代码:

注意: 代码已在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")

}

答案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")

}

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

2020-07-07