Swift:如何创建自定义UINavigationBar并添加自定义后退按钮?

时间:2017-06-24 08:49:43

标签: ios swift uinavigationbar

我正在尝试创建自定义navigationBar。

我在viewWillAppear中隐藏原始的navigationBar,如下所示:

B

我像这样继承UINavigationBar:

override func viewWillAppear(_ animated: Bool) {
    self.navigationController?.isNavigationBarHidden = true
}

在viewDidLoad中我调用setupNavBar():

let navBar: UINavigationBar = {
    let view = UINavigationBar()
    view.backgroundColor = .clear
    view.isTranslucent = true
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

问题是backButton被添加到正在隐藏的原始navigationBar中。这让我觉得我错误地创建了navigationBar。如何将按钮添加到navBar?

更新的代码(仍无效):

func setupNavBar() {
    view.addSubview(navBar)
    self.navBar.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 80)
    let backButton = UIBarButtonItem(image: UIImage(named:"backThick"), style: .plain, target: self, action: #selector(popControllerOffStack))       
}

See this pic: The button is being added to the original navigationBar

3 个答案:

答案 0 :(得分:3)

您不是UINavigationBar的子类。相反,您正在创建UINavigationBar的新实例并在计算变量内修改其属性。这意味着每次访问navBar时,您都要初始化一个新的UINavigationBar对象。

创建子类:

class MyCustomNavigationBar: UINavigationBar {
    // Set properties in here after initialization
}

一旦你创建了一个合适的子类,就可以像这样初始化一个实例:

var navBar = MyCustomNavigationBar()

最后,将您的按钮添加到导航栏:

let backButton = UIBarButtonItem(image: UIImage(named:"backThick"), style: .plain, target: self, action: #selector(popControllerOffStack))  
// Assuming 'self' is an instance of UINavigationController()     
self.navigationItem.leftBarButtonItem = backButton

见官方Swift Programming Language Guide on Inheritance

答案 1 :(得分:0)

Swift 3.0

您可以设置自定义后退按钮,如下所示

  self.navigationItem.hidesBackButton = true
    let backButton = UIBarButtonItem(image: UIImage(named: "image_name"), style: .plain, target: self, action: #selector(Class.methodName))
    backButton.tintColor = UIColor.white
    self.navigationItem.leftBarButtonItem = backButton

答案 2 :(得分:0)

您也可以尝试以下代码:

let btnLeftMenu: UIButton = UIButton()
btnLeftMenu.setImage(UIImage(named: "image_name"), for:UIControlState())
btnLeftMenu.addTarget(self, action: #selector(moveImage), for:UIControlEvents.touchUpInside)
btnLeftMenu.frame = CGRect(x: 0, y: 0, width: 25, height: 25)
let barButton = UIBarButtonItem(customView: btnLeftMenu)
self.navigationItem.leftBarButtonItem = barButton*