iOS项目开发实战(Swift)—初探UITabbarController和UINavigationController的集成

1.UITabbarController

分栏控制器,用来进行ViewController页面的切换,这些页面是并列的。最下面一栏是Tabbar,其中的按钮是TabbarItem


2.UINavigationController

导航控制器,也是用来进行ViewController页面的切换,但这些页面不是并列,有层次关系。最上面一栏是Navigationbar,用navigationItem进行管理。


3.UITabbarController和UINavigationController的集成

eg:首页的集成,代码如下:

        let homepageController = homepageViewController()
        //一定要将homepageController作为UINavigationController的根视图
        let hc = UINavigationController(rootViewController: homepageController)
        //tabbarItem的标题
        hc.tabBarItem.title = "首页"
        tabbarController.addChildViewController(hc)

4.主要代码如下:

//  AppDelegate.swift
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?.backgroundColor = UIColor.whiteColor()

        let tabbarController = UITabBarController()
        self.window?.rootViewController = tabbarController

        let homepageController = homepageViewController()
        //一定要将homepageController作为UINavigationController的根视图
        let hc = UINavigationController(rootViewController: homepageController)
        //tabbarItem的标题
        hc.tabBarItem.title = "首页"
        tabbarController.addChildViewController(hc)
        
        let categoryController = categoryViewController()
        let cc = UINavigationController(rootViewController: categoryController)
        cc.tabBarItem.title = "分类"
        tabbarController.addChildViewController(cc)
        
        let discoveryController = discoveryViewController()
        let dc = UINavigationController(rootViewController: discoveryController)
        dc.tabBarItem.title = "发现"
        tabbarController.addChildViewController(dc)
        
        let personalController = personalViewController()
        let pc = UINavigationController(rootViewController: personalController)
        pc.tabBarItem.title = "我的"
        tabbarController.addChildViewController(pc)
        
        self.window?.makeKeyAndVisible()

        return true
    }

    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:.
    }


}


//  homepageViewController.swift
import UIKit

class homepageViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    var baby = ["宝宝0","宝宝1","宝宝2","宝宝3","宝宝4","宝宝5","宝宝6","宝宝7","宝宝8","宝宝9","宝宝10","宝宝11"]
    
    var babyImage = ["宝宝0.jpg","宝宝1.jpg","宝宝2.jpg","宝宝3.jpg","宝宝4.jpg","宝宝5.jpg","宝宝6.jpg","宝宝7.jpg","宝宝8.jpg","宝宝9.jpg","宝宝10.jpg","宝宝11.jpg"]
    
//    var isMark = Array(count:12,repeatedValue:false)
    var isMark = [Bool](count: 12, repeatedValue: false)
    
    var tableView = UITableView()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "首页"
        self.view.backgroundColor = UIColor.whiteColor()

        tableView = UITableView(frame: CGRectMake(0, 0, 320, 660), style: UITableViewStyle.Plain)
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return baby.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let initIdentifier = "Cell"
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: initIdentifier)
        cell.textLabel?.text = baby[indexPath.row]
//        cell.detailTextLabel是subtitle风格用的二级文本
        
        let imageName = babyImage[indexPath.row]
        cell.imageView?.image = UIImage(named: imageName)
        cell.accessoryType = UITableViewCellAccessoryType.DetailButton
        
        if isMark[indexPath.row] {
            cell.accessoryType = UITableViewCellAccessoryType.Checkmark
        }else{
            cell.accessoryType = UITableViewCellAccessoryType.None
        }
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//        print("sisi")
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
        let cancleAction = UIAlertAction(title: "Cancle", style: UIAlertActionStyle.Cancel, handler: nil)
        alertController.addAction(cancleAction)
        
        let markAction = UIAlertAction(title: "标记宝宝一下", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction) -> Void in
            let cell = tableView.cellForRowAtIndexPath(indexPath)
            cell?.accessoryType = UITableViewCellAccessoryType.Checkmark
            self.isMark[indexPath.row] = true
        })
        alertController.addAction(markAction)
        
        let guessHandler = {(action: UIAlertAction) -> Void in
            let guessActionController = UIAlertController(title: nil, message: "我是宝宝\(indexPath.row)", preferredStyle: UIAlertControllerStyle.Alert)
            
            let cancleAction = UIAlertAction(title: "Cancle", style: UIAlertActionStyle.Cancel, handler: nil)
            guessActionController.addAction(cancleAction)
            
            self.presentViewController(guessActionController, animated: true, completion: nil)
        }
        let guessAction = UIAlertAction(title: "猜猜宝宝几号", style: UIAlertActionStyle.Default, handler: guessHandler)
        //guessHandler写在前面就不会crash,如果是下面这样就会crash
        
//        let guessAction = UIAlertAction(title: "猜猜宝宝几号", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction) -> Void in
//            let guessActionController = UIAlertController(title: nil, message: "我是宝宝\(indexPath.row)", preferredStyle: UIAlertControllerStyle.Alert)
//            
//            let cancleAction = UIAlertAction(title: "Cancle", style: UIAlertActionStyle.Cancel, handler: nil)
//            guessActionController.addAction(cancleAction)
//            
//            self.presentViewController(guessActionController, animated: true, completion: nil)
//        })
        alertController.addAction(guessAction)
        presentViewController(alertController, animated: true, completion: nil)
    }
    
    func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
        let shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Share", handler: {(action: UITableViewRowAction, indexPath: NSIndexPath) -> Void in
            let shareController = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
            
            let cancleAction = UIAlertAction(title: "Cancle", style: UIAlertActionStyle.Cancel, handler: nil)
            shareController.addAction(cancleAction)
            
            let facebookAction = UIAlertAction(title: "Facebook", style: UIAlertActionStyle.Default, handler: nil)
            shareController.addAction(facebookAction)
            
            let twitterAction = UIAlertAction(title: "Twitter", style: UIAlertActionStyle.Default, handler: nil)
            shareController.addAction(twitterAction)
            self.presentViewController(shareController, animated: true, completion: nil)
        })
        
        let deleteAction = UITableViewRowAction(style: .Default, title: "Delete", handler: {
            (action: UITableViewRowAction, indexPath: NSIndexPath) -> Void in
            //清除数据
            self.baby.removeAtIndex(indexPath.row)
            self.babyImage.removeAtIndex(indexPath.row)
            self.isMark.removeAtIndex(indexPath.row)
            //删除某行
            self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
//            print(indexPath.row)
            
        })
        
        return [shareAction,deleteAction]
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete {
            baby.removeAtIndex(indexPath.row)
            babyImage.removeAtIndex(indexPath.row)
            isMark.removeAtIndex(indexPath.row)
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


5.成功运行如下:

iOS项目开发实战(Swift)—初探UITabbarController和UINavigationController的集成_第1张图片iOS项目开发实战(Swift)—初探UITabbarController和UINavigationController的集成_第2张图片

你可能感兴趣的:(iOS项目开发实战(Swift)—初探UITabbarController和UINavigationController的集成)