如果您正在寻找通用的自定义导航菜单,请尝试此代码
func setupPageNavigationBar(){
navigationController?.navigationBar.barTintColor = UIColor(red:1.00, green:0.22, blue:0.22, alpha:1.0)
navigationController?.navigationBar.translucent = false
let backButton = UIButton(type:.System)
backButton.setImage(UIImage(named: "img_back")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Normal)
backButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let imgButton = UIButton(type:.System)
imgButton.setImage(UIImage(named: "img_logo_bar")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Normal)
imgButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
navigationItem.leftBarButtonItems = [UIBarButtonItem(customView: backButton),UIBarButtonItem(customView:imgButton)]
backButton.addTarget(self, action: #selector(self.goBack), forControlEvents: .TouchUpInside)
let titleLabel = UILabel()
titleLabel.text = "SOME TITLE"
let titleLabel2 = UILabel()
titleLabel2.text = "Some text"
titleLabel.font = UIFont.boldSystemFontOfSize(15)
titleLabel.textColor = UIColor.whiteColor()
titleLabel.textAlignment = .Left
titleLabel2.font = UIFont.systemFontOfSize(11)
titleLabel2.textColor = UIColor.whiteColor()
titleLabel2.textAlignment = .Left
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: view.frame.width-90, height: 50)
//titleView.backgroundColor = UIColor.whiteColor()
titleView.addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleView.addSubview(titleLabel2)
titleLabel2.translatesAutoresizingMaskIntoConstraints = false
//titleLabel.frame = CGRect(x: 0, y: 0, width: 134, height: 34)
let viewDict = ["titleLabel":titleLabel,"titleLabel2":titleLabel2]
titleView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[titleLabel]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views: viewDict))
titleView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[titleLabel2]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views: viewDict))
titleView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-5-[titleLabel(20)]-0-[titleLabel2(15)]", options: NSLayoutFormatOptions(), metrics: nil, views: viewDict))
//5+20+5+15+5
navigationItem.titleView = titleView
let homeButton = UIButton(type:.System)
homeButton.setImage(UIImage(named: "img_home")?.imageWithRenderingMode(.AlwaysOriginal), forState: .Normal)
homeButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: homeButton)
homeButton.addTarget(self, action: #selector(self.gotoHome), forControlEvents: .TouchUpInside)
//CGRectMake()
}
在视图控制器中
override func viewDidLayoutSubviews()
{
self.setupPageNavigationBar()
}