不使用storyboard布局,将其删除,全代码写
在appDelegate中创建窗口
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//1. 创建窗口
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
//2. 显示窗口
self.window?.makeKeyAndVisible()
let viewCtrl = ViewController()
// self.window?.rootViewController = viewCtrl
//3. 创建导航控制器,至少需要放入一个页面(第一个页面也叫做根视图控制器)
let navCtrl = UINavigationController(rootViewController: viewCtrl)
//文字/图片
navCtrl.navigationBar.tintColor = UIColor.redColor()
//整个导航条的颜色
navCtrl.navigationBar.barTintColor = UIColor.greenColor()
self.window?.rootViewController = navCtrl
return true
}
ViewController中
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.redColor()
// self.title = "第一页"
//用于设置导航条
// self.navigationItem.title = "第一页"
//设置导航条中间部分
let v = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 10))
v.backgroundColor = UIColor.blueColor()
self.navigationItem.titleView = v
//设置左侧
// self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "左侧", style: .Plain, target: self, action: #selector(leftClicked))
// self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Bookmarks, target: self, action: #selector(leftClicked))
let originImage = UIImage(named: "1.png")
//图片总是显示原始颜色
let image = originImage?.imageWithRenderingMode(.AlwaysOriginal)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style: .Plain, target: self, action: #selector(leftClicked))
let btn = UIButton(type: .System)
btn.frame = CGRect(x: self.view.frame.size.width / 2 - 75, y:self.view.frame.size.height / 2 - 25, width: 150, height: 50)
btn.setTitle("下一页", forState: .Normal)
btn.addTarget(self, action: #selector(didClicked(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(btn)
}
func leftClicked() {
print("leftClicked")
}
func didClicked(sender: UIButton) {
let secondCtrl = SecondViewController()
//每一个“已经”处于导航控制器中的页面,它的navigationController属性不为空
self.navigationController?.pushViewController(secondCtrl, animated: true)
}
deinit {
print("first")
}
}
新建第二个SecondViewControl
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//设置背景色
self.view.backgroundColor = UIColor.greenColor()
}
//点击任意地方返回第一页
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.navigationController?.popViewControllerAnimated(true)
}
//返回后让其销毁
deinit {
print("second")
}
}
PS:导航栏的默认高度为66个像素,上面默认留20个像素(时间,电量部分),下面44个像素