[Swift通天遁地]九、拔剑吧-(6)使用开源类库快速搭建强大的侧边栏项目

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10356341.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

目录:[Swift]通天遁地Swift

本文将演示给项目快速添加一个侧边栏

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,  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 }

原文地址:https://www.cnblogs.com/strengthen/p/10356341.html