UINavigationController
UINavigationController即有导航栏的的UIViewController.它可以非常方便的进行界面的切换.
1. UINavigationController的创建
首先我们创建一个UINavigationController, 修改AppDelegate.swift
// ViewController.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let vc = ViewController()
let nav = UINavigationController(rootViewController: vc)
window?.rootViewController = nav
window?.makeKeyAndVisible()
return true
}
在这个方法中, 我们创建了一个UINavigationController, 并设置了rootViewController.然后我们使用第4课中的ViewController和ViewController2类, 简单的修改一下即可
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.title = "ViewController"
let button = UIButton(type: .Custom)
button.frame = CGRect(x: 0, y: 100, width: 100, height: 40)
// 设置不同状态文字
button.setTitle("Normal", forState: .Normal)
button.setTitle("Highlighted", forState: .Highlighted)
button.setTitle("Disabled", forState: .Disabled)
// 设置不同状态文字颜色
button.setTitleColor(UIColor.redColor(), forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Highlighted)
button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
button.setBackgroundImage(UIImage(named: "normal"), forState: .Normal)
button.setBackgroundImage(UIImage(named: "highlighted"), forState: .Highlighted)
button.setBackgroundImage(UIImage(named: "disabled"), forState: .Disabled)
button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func buttonAction(sender: UIButton) {
// 跳转到ViewController2
let vc = ViewController2()
vc.age = 100
self.navigationController?.pushViewController(vc, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
import UIKit
class ViewController2: UIViewController {
var age: Int?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red: 0xff/255.0, green: 0x00/255.0, blue: 0xff/255.0, alpha: 1.0)
self.title = "ViewController2"
let button = UIButton(type: .Custom)
button.frame = CGRect(x: 0, y: 200, width: 100, height: 40)
// 设置不同状态文字
button.setTitle("返回", forState: .Normal)
button.setTitle("返回", forState: .Highlighted)
button.setTitle("返回", forState: .Disabled)
// 设置不同状态文字颜色
button.setTitleColor(UIColor.redColor(), forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Highlighted)
button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
button.setBackgroundImage(UIImage(named: "normal"), forState: .Normal)
button.setBackgroundImage(UIImage(named: "highlighted"), forState: .Highlighted)
button.setBackgroundImage(UIImage(named: "disabled"), forState: .Disabled)
button.addTarget(self, action: "backAction:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func backAction(sender: UIButton) {
// 返回
self.navigationController?.popViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
现在运行程序
我们可以发现屏幕上面多个矩形方块部分, 这部分就是导航栏.
2. UINavigationController的界面的跳转
界面的跳转使用:
self.navigationController?.pushViewController(vc, animated: true)
第一个参数是要跳转到的UIViewController.
第二个参数是是否有动画效果
返回
self.navigationController?.popViewControllerAnimated(true)
参数是是否有动画效果
参数传递的方式和UIViewController一样
3. 设置导航栏的颜色,标题颜色,按钮颜色
修改AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.navBarConfig()
let vc = ViewController()
let nav = UINavigationController(rootViewController: vc)
window?.rootViewController = nav
window?.makeKeyAndVisible()
return true
}
func navBarConfig() {
let bar = UINavigationBar.appearance()
//设置导航栏的颜色
bar.barTintColor = UIColor(red: 0xff/255.0, green: 0x52/255.0, blue: 0x56/255.0, alpha: 1.0)
//设置按钮的颜色
bar.tintColor = UIColor.whiteColor()
// 设置标题颜色
bar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()];
// 导航栏是否半透明
bar.translucent = false
}
运行程序:
我们可以发现导航栏的颜色, 标题颜色,按钮颜色都编程我们设置的值了.
使用UINavigationBar.appearance()可以设置所有的导航栏的属性, 如果需要设置个别的UIViewController的导航栏的属性, 设置self.navigationController?.navigationBar的属性即可.如:
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
4. 添加导航栏按钮
有时候我们需要添加给导航栏添加按钮, 如在导航栏右侧添加一个详情按钮.
// ViewController2.swift
override func viewDidLoad() {
super.viewDidLoad()
...
// 添加导航栏详情按钮
let detailBtn = UIBarButtonItem(title: "详情", style: .Plain, target: self, action: "detailAction:")
self.navigationItem.rightBarButtonItem = detailBtn
}
func detailAction(sender: UIBarButtonItem) {
print("跳转到详情\(sender.title)")
}
运行程序,我们发现导航栏右侧多了个详情按钮,点击它控制台打印”跳转到详情Optional(“详情”)”
注意:导航栏的按钮使用的是UIBarButtonItem,而不是UIButton,它也可以设置图片,使用一个新的类的时候一定要点进去看看这个类都有哪些方法.下面列举它的几个构造方法,具体使用不在详述
public init()
public init?(coder aDecoder: NSCoder)
public convenience init(image: UIImage?, style: UIBarButtonItemStyle, target: AnyObject?, action: Selector)
@available(iOS 5.0, *)
public convenience init(image: UIImage?, landscapeImagePhone: UIImage?, style: UIBarButtonItemStyle, target: AnyObject?, action: Selector) // landscapeImagePhone will be used for the bar button image when the bar has Compact or Condensed bar metrics.
public convenience init(title: String?, style: UIBarButtonItemStyle, target: AnyObject?, action: Selector)
public convenience init(barButtonSystemItem systemItem: UIBarButtonSystemItem, target: AnyObject?, action: Selector)
public convenience init(customView: UIView)
5. 完整代码:
AppDelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.navBarConfig()
let vc = ViewController()
let nav = UINavigationController(rootViewController: vc)
window?.rootViewController = nav
window?.makeKeyAndVisible()
return true
}
func navBarConfig() {
let bar = UINavigationBar.appearance()
//设置导航栏的颜色
bar.barTintColor = UIColor(red: 0xff/255.0, green: 0x52/255.0, blue: 0x56/255.0, alpha: 1.0)
//设置按钮的颜色
bar.tintColor = UIColor.whiteColor()
// 设置标题颜色
bar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()];
// 导航栏是否半透明
bar.translucent = false
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.title = "ViewController"
let button = UIButton(type: .Custom)
button.frame = CGRect(x: 0, y: 100, width: 100, height: 40)
// 设置不同状态文字
button.setTitle("Normal", forState: .Normal)
button.setTitle("Highlighted", forState: .Highlighted)
button.setTitle("Disabled", forState: .Disabled)
// 设置不同状态文字颜色
button.setTitleColor(UIColor.redColor(), forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Highlighted)
button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
button.setBackgroundImage(UIImage(named: "normal"), forState: .Normal)
button.setBackgroundImage(UIImage(named: "highlighted"), forState: .Highlighted)
button.setBackgroundImage(UIImage(named: "disabled"), forState: .Disabled)
button.addTarget(self, action: "buttonAction:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func buttonAction(sender: UIButton) {
// 跳转到ViewController2
let vc = ViewController2()
vc.age = 100
self.navigationController?.pushViewController(vc, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
var age: Int?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red: 0xff/255.0, green: 0x00/255.0, blue: 0xff/255.0, alpha: 1.0)
self.title = "ViewController2"
let button = UIButton(type: .Custom)
button.frame = CGRect(x: 0, y: 200, width: 100, height: 40)
// 设置不同状态文字
button.setTitle("返回", forState: .Normal)
button.setTitle("返回", forState: .Highlighted)
button.setTitle("返回", forState: .Disabled)
// 设置不同状态文字颜色
button.setTitleColor(UIColor.redColor(), forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Highlighted)
button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
button.setBackgroundImage(UIImage(named: "normal"), forState: .Normal)
button.setBackgroundImage(UIImage(named: "highlighted"), forState: .Highlighted)
button.setBackgroundImage(UIImage(named: "disabled"), forState: .Disabled)
button.addTarget(self, action: "backAction:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
// 添加导航栏详情按钮
let detailBtn = UIBarButtonItem(title: "详情", style: .Plain, target: self, action: "detailAction:")
self.navigationItem.rightBarButtonItem = detailBtn
}
func detailAction(sender: UIBarButtonItem) {
print("跳转到详情\(sender.title)")
}
func backAction(sender: UIButton) {
// 返回
self.navigationController?.popViewControllerAnimated(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}