在Swift中设置导航栏高度

时间:2016-04-19 11:59:53

标签: ios swift height uinavigationbar

我是斯威夫特的新手。我试图改变(增加)导航栏的高度。有什么明显的方法吗? (我试图用CGRectMake改变它,但是它在条形图上生成了一个矩形,我丢失了后退按钮等。)这是最好的实现方法吗?

4 个答案:

答案 0 :(得分:0)

根据苹果指南,您不应尝试更改导航栏的大小。如果需要,您应该使用自定义导航栏。希望这会有所帮助:)

答案 1 :(得分:0)

我们可以使用继承方法。

1)创建UIViewController的父控制器。将其命名为UIAppViewController。

//  UIAppViewController.swift

import UIKit

class UIAppViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

    }
    override func viewWillAppear(animated: Bool) {

    }
    func addCustomNavigationBarToView()
    {
        // Create the navigation bar
        let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 84))

        // Create a navigation item with a title
        let navigationItem = UINavigationItem()
        navigationItem.title = "Title"

        // Create left and right button for navigation item
        let leftButton =  UIBarButtonItem(title: "Save", style:   UIBarButtonItemStyle.Plain, target: self, action: "saveButtonClicked:")
        let rightButton = UIBarButtonItem(title: "Right", style: UIBarButtonItemStyle.Plain, target: self, action: nil)

        // Create two buttons for the navigation item
        navigationItem.leftBarButtonItem = leftButton
        navigationItem.rightBarButtonItem = rightButton

        // Assign the navigation item to the navigation bar
        navigationBar.items = [navigationItem]

        // Make the navigation bar a subview of the current view controller
        self.view.addSubview(navigationBar)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

请注意,我已经制作了一个方法,可以在self.view中添加自定义导航栏。

2)在ViewController上:

//  ViewController.swift

import UIKit

class ViewController: UIAppViewController,UITextFieldDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func viewWillAppear(animated: Bool) {
        self.navigationController?.navigationBarHidden =  false
        self.addCustomNavigationBarToView()

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
}

答案 2 :(得分:0)

子类化UINavigationBar也是一种解决方案。

File-New-File- iOS Source - Cocoa Touch类 - 选择子类:UINavigationBar并命名为 - CustomNavigationBar。

class CustomNavigationBar: UINavigationBar {

    override init(frame: CGRect) {
        super.init(frame: frame)

//Change here

        self.backgroundColor = UIColor.redColor()

    }
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }
    override func drawRect(rect: CGRect) {

//set frame.

    }   
}

答案 3 :(得分:-1)

试试这段代码:

func sizeThatFits(size: CGSize) -> CGSize 
{
        var newSize: CGSize = CGSizeMake(self.frame.size.width, 70)
        return newSize
    }