1. 程式人生 > >[Swift通天遁地]九、拔劍吧-(6)使用開源類庫快速搭建強大的側邊欄項目

[Swift通天遁地]九、拔劍吧-(6)使用開源類庫快速搭建強大的側邊欄項目

opengl es 使用 scroll restart election state exe mov 索引

本文將演示給項目快速添加一個側邊欄

Github項目地址:【ENSwiftSideMenu

下載項目,解壓文件。

【Library】->【ENSwiftSideMenu.swift

->按下【Shift】,選擇【ENSwiftSideMenuController.swift

->將選擇的兩個文件,拖動到項目中。

在彈出的文件導入確認窗口中,點擊【Finish】完成,確認文件的導入。

接著創建用於側邊欄的三個視圖控制器,

在項目文件夾上點擊鼠標右鍵,彈出右鍵菜單。

【New File->【Cocoa Touch->【Next】->

【Class】:SubViewController1

【Subclass of:UIViewController

【Language】:Swift

->Next->【Create】

點擊打開【SubViewController1.swift】,現在開始編寫代碼,開始設置該頁面的外觀。

 1 import UIKit
 2 
 3 class SubViewController1: UIViewController {
 4 
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
7 // Do any additional setup after loading the view. 8 9 //初始化一個圖像視圖,用來顯示項目中的一張圖片。 10 let imageView = UIImageView(image: UIImage(named: "Animal")) 11 //將圖像視圖添加到根視圖, 12 self.view.addSubview(imageView) 13 } 14 15 override func didReceiveMemoryWarning() {
16 super.didReceiveMemoryWarning() 17 // Dispose of any resources that can be recreated. 18 } 19 }

同理創建控制器文件【SubViewController2.swift

 1 import UIKit
 2 
 3 class SubViewController2: UIViewController {
 4 
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7 
 8         // Do any additional setup after loading the view.
 9         //設置根視圖的背景顏色為橙色
10         self.view.backgroundColor = UIColor.orange
11     }
12 
13     override func didReceiveMemoryWarning() {
14         super.didReceiveMemoryWarning()
15         // Dispose of any resources that can be recreated.
16     }
17 }

同理創建控制器文件【SubViewController3.swift

 1 import UIKit
 2 
 3 class SubViewController3: UIViewController {
 4 
 5     override func viewDidLoad() {
 6         super.viewDidLoad()
 7         // Do any additional setup after loading the view.
 8         //初始化一個圖像視圖,用來顯示項目中的一張圖片。
 9         let imageView = UIImageView(image: UIImage(named: "Girl"))
10         //將圖像視圖添加到根視圖
11         self.view.addSubview(imageView)
12     }
13 
14     override func didReceiveMemoryWarning() {
15         super.didReceiveMemoryWarning()
16         // Dispose of any resources that can be recreated.
17     }
18 }

在項目文件夾上點擊鼠標右鍵,彈出右鍵菜單。

【New File->【Cocoa Touch->【Next】->

【Class】:MenuViewController

【Subclass of:UITableViewController

【Language】:Swift

->Next->【Create】

點擊打開【MenuViewController.swift】,現在開始編寫代碼,開始設置該頁面的外觀。

現在開始編寫表格視圖控制器,該控制器將作為項目的側邊欄。

  1 import UIKit
  2 
  3 class MenuViewController: UITableViewController {
  4 
  5     //添加一個整形屬性,表示當前選擇的菜單索引。
  6     var selectedMenuItem : Int = 0
  7     
  8     override func viewDidLoad() {
  9         super.viewDidLoad()
 10         // Do any additional setup after loading the view.
 11         
 12         //設置根視圖的背景顏色為無色
 13         self.view.backgroundColor = UIColor.clear
 14         //並設置在視圖即將顯示時,清除之前已有的對單元格的選擇。
 15         self.clearsSelectionOnViewWillAppear = false
 16         
 17         //設置表格視圖的內間距
 18         tableView.contentInset = UIEdgeInsets(top: 64.0, left: 0, bottom: 0, right: 0)
 19         //清除表格視圖中的單元格之間的分割線
 20         tableView.separatorStyle = .none
 21         //設置當點擊頂部狀態欄時,表格不會滾動至頂部。
 22         tableView.scrollsToTop = false
 23         
 24         //初始化一個索引路徑對象,並設置它的行數,為當前類的屬性的值。它的段落索引為0。
 25         let indexPath = IndexPath(row: selectedMenuItem, section: 0)
 26         //使表格視圖選擇位於指定索引路徑的單元格。
 27         tableView.selectRow(at: indexPath, animated: false, scrollPosition: .middle)
 28     }
 29 
 30     //添加一個代理方法,用來設置表格的段落數量為1。
 31     override func numberOfSections(in tableView: UITableView) -> Int
 32     {
 33         return 1
 34     }
 35     
 36     //添加一個代理方法,用來設置表格的行數,在此設置表格擁有4行單元格。
 37     override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
 38     {
 39         return 4
 40     }
 41     
 42     //添加一個代理方法,用來初始化或復用表格中的單元格。
 43     override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
 44     {
 45         //創建一個字符串常量,作為單元格的復用標識。
 46         let identifier = "CELL"
 47         //根據復用標識,從表格中獲取可以復用的單元格。
 48         var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
 49         
 50         //如果沒有復用的單元格,則初始化一個自定義的單元格。
 51         if(cell == nil)
 52         {
 53              //並設置單元格的復用標識。
 54             cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: identifier)
 55             //設置單元格的背景顏色為無色
 56             cell!.backgroundColor = UIColor.clear
 57             //以及單元格標題文字的顏色為深色
 58             cell!.textLabel?.textColor = UIColor.darkGray
 59             
 60             //初始化一個和單元格相同尺寸的矩形區域
 61             let frame = CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height)
 62             //創建一個指定顯示區域的視圖對象,作為單元格處於焦點狀態時的背景視圖。
 63             let selectedBackgroundView = UIView(frame: frame)
 64             //設置視圖對象的背景顏色為灰色,並設置顏色的不透明度為0.2
 65             selectedBackgroundView.backgroundColor = UIColor.gray.withAlphaComponent(0.2)
 66             //設置單元格處於焦點狀態時的背景視圖
 67             cell!.selectedBackgroundView = selectedBackgroundView
 68         }
 69         
 70         //設置單元格的標題文字
 71         cell!.textLabel?.text = "ViewController #\(indexPath.row+1)"
 72         //設置單元格標題的字體屬性
 73         cell!.textLabel?.font = UIFont(name: "Arial", size: 12)
 74         
 75         //返回設置好的單元格
 76         return cell!
 77     }
 78     
 79     //添加一個代理方法,用來設置單元格的高度,
 80     override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
 81     {
 82         //這裏設置單元格的高度為50
 83         return 50
 84     }
 85     
 86     //添加一個方法,用來處理單元格的觸摸事件
 87     override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
 88     {
 89         //在控制臺輸出當前選擇的行號
 90         print("did select row: \(indexPath.row)")
 91         
 92         //如果重復點擊來處於選擇狀態的單元格,則不再執行方面的代碼
 93         if (indexPath.row == selectedMenuItem)
 94         {
 95             return
 96         }
 97         
 98         //將處於選擇狀態的單元格行號,賦予該屬性,
 99         //當用標識處於選擇狀態的單元格。
100         selectedMenuItem = indexPath.row
101         
102         //添加一個視圖控制器變量。
103         var destViewController : UIViewController
104         //根據選擇的行號的不同,使用不同的類對變量進行初始化。
105         switch (indexPath.row)
106         {
107             //當選擇第一行單元格時
108             case 0:
109                 //初始化一個自帶的視圖控制器
110                 //也就是用戶點擊該單元格時,顯示該視圖控制器下的內容。
111                 destViewController = UIViewController()
112                 break
113             //當選擇第二行單元格時,
114             case 1:
115                  //初始化第一個自定義的視圖控制器。
116                 destViewController = SubViewController1()
117                 break
118             //當選擇第三行單元格時,
119             case 2:
120                 //初始化第二個自定義的視圖控制器。
121                 destViewController = SubViewController2()
122                 break
123             //當選擇第四行單元格時,
124             default:
125                  //初始化第三個自定義的視圖控制器。
126                 destViewController = SubViewController3()
127                 break
128         }
129         
130         //使用視圖控制器的擴展方法,獲得側邊欄的控制器,
131         //並設置它的內容視圖控制器屬性。
132         sideMenuController()?.setContentViewController(destViewController)
133     }
134     
135     override func didReceiveMemoryWarning() {
136         super.didReceiveMemoryWarning()
137         // Dispose of any resources that can be recreated.
138     }
139 }

在項目文件夾上點擊鼠標右鍵,彈出右鍵菜單。

創建一個側邊欄導航控制器。

【New File->【Cocoa Touch->【Next】->

【Class】:RootNavigationViewController

【Subclass of:ENSideMenuNavigationController

【Language】:Swift

->Next->【Create】

點擊打開【RootNavigationViewController.swift】

現在開始編寫代碼,創建一個側邊欄控制器。

 1 import UIKit
 2 
 3 //首先給類添加一個代理協議,用來監聽側邊欄的開啟和關閉事件。
 4 class RootNavigationViewController: ENSideMenuNavigationController, ENSideMenuDelegate {
 5     
 6     override func viewDidLoad() {
 7         super.viewDidLoad()
 8         // Do any additional setup after loading the view.
 9         
10         //設置視圖的背景顏色,在此使用一幅圖片,對根視圖進行平鋪。
11         self.view.backgroundColor = UIColor(patternImage: UIImage(named: "Sample")!)
12         //初始化一個側邊欄,並設置側邊欄的源視圖、側邊欄控制器和側邊欄的位置。
13         //側邊欄的位置共有左、右兩種。
14         sideMenu = ENSideMenu(sourceView: self.view, menuViewController: MenuViewController(), menuPosition:.left)
15         
16         //設置側邊欄的代理對象
17         sideMenu?.delegate = self
18         //設置側邊欄允許滑動手勢
19         sideMenu?.allowPanGesture = true
20         //關閉側邊欄打開和關閉時的彈性動畫
21         sideMenu?.bouncingEnabled = false
22         //設置側邊欄的寬度為180.0
23         sideMenu?.menuWidth = 180.0
24     }
25     
26     //添加一個方法,用來監聽側邊欄即將打開的事件
27     func sideMenuWillOpen()
28     {
29         print("sideMenuWillOpen")
30     }
31     
32      //添加一個方法,用來監聽側邊欄即將關閉時的事件
33     func sideMenuWillClose()
34     {
35         print("sideMenuWillClose")
36     }
37     
38      //添加一個方法,用來監聽側邊欄關閉的事件
39     func sideMenuDidClose()
40     {
41         print("sideMenuDidClose")
42     }
43     
44      //添加一個方法,用來監聽側邊欄打開的事件
45     func sideMenuDidOpen()
46     {
47         print("sideMenuDidOpen")
48     }
49     
50     func sideMenuShouldOpenSideMenu() -> Bool {
51         return true
52     }
53     
54     override func didReceiveMemoryWarning() {
55         super.didReceiveMemoryWarning()
56         // Dispose of any resources that can be recreated.
57     }
58 }

打開應用程序的代理文件【AppDelegate.swift】

 1 import UIKit
 2 
 3 @UIApplicationMain
 4 class AppDelegate: UIResponder, UIApplicationDelegate {
 5 
 6     var window: UIWindow?
 7 
 8 
 9     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
10         // Override point for customization after application launch.
11         
12         //在應用程序完成加載的方法中,創建一個導航視圖控制器。
13         //在初始化導航視圖控制器時,依次設置它的菜單控制器屬性,和內容控制器屬性。
14         let navVc = RootNavigationViewController(menuViewController: MenuViewController(), contentViewController: UIViewController())
15         
16         //將該導航視圖控制器,作為當前窗口的根視圖控制器。
17         self.window?.rootViewController = navVc
18         return true
19     }
20 
21     func applicationWillResignActive(_ application: UIApplication) {
22         // 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.
23         // 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.
24     }
25 
26     func applicationDidEnterBackground(_ application: UIApplication) {
27         // 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.
28         // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
29     }
30 
31     func applicationWillEnterForeground(_ application: UIApplication) {
32         // 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.
33     }
34 
35     func applicationDidBecomeActive(_ application: UIApplication) {
36         // 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.
37     }
38 
39     func applicationWillTerminate(_ application: UIApplication) {
40         // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
41     }
42 }

[Swift通天遁地]九、拔劍吧-(6)使用開源類庫快速搭建強大的側邊欄項目