导航栏的设置与处理
*首先创建一个视图,并创建好导航栏管理控件
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//创建一个窗口
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
//使窗口可见
self.window?.makeKeyAndVisible()
//关联ViewController
let viewCrt = ViewController()
//创建导航栏管理器
let navCrt = UINavigationController(rootViewController: viewCrt)
self.window?.rootViewController = navCrt
//设置导航栏颜色
navCrt.navigationBar.barTintColor = UIColor.redColor()
//设置导航栏上所有添加上去的视图颜色(包括label和button/image)
navCrt.navigationBar.tintColor = UIColor.blackColor()
return true
}
*然后进行添加导航栏上的东西
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
//创建一个系统button
let button = UIButton(type: .System)
button.frame = CGRect(x: self.view.frame.size.width / 2 - 50, y: self.view.frame.size.height / 2 - 25, width: 100, height: 50)
button.tintColor = UIColor.redColor()
button.setTitle("first page", forState: .Normal)
button.addTarget(self, action: #selector(didClick(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(button)
//设置导航栏上的中间title内容,默认为居中
self.navigationItem.title = "首页"
//设置系统的图标摆放至导航栏左侧
// self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: #selector(didClick(_:)))
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Done, target: self, action: nil)
//设置导航栏右侧内容,添加一个button,点击触发事件为didClick
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "下一页", style: .Plain, target: self, action: #selector(didClick(_:)))
}
func didClick(sender: UIButton){
let seconde = secondeViewController()
//以栈的形式将第二个页面弹出(push)
self.navigationController?.pushViewController(seconde, animated: true)
}
deinit {
print("first")
}
}
*触发点击事件,创建第二个页面,第二个页面的代码如下:
import UIKit
class secondeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.greenColor()
}
//设置默认的返回点击页面(以栈的方式将之前的页面返回,pop)
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.navigationController?.popViewControllerAnimated(true)
}
deinit {
print("second")
}
}