Swift - 第三方侧栏菜单组件SideMenu使用详解3(使用纯代码实现)
作者:hangge | 2019-03-20 08:30
四、使用纯代码实现侧栏菜单
1,侧栏菜单的定义
我们继承 UITableViewController 来定义一个表格来作为侧栏菜单,表格内有三个单元格。
import UIKit
// 菜单视图控制器
class MenuViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
//创建一个重用的单元格
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "myCell")
}
// 分区数
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// 单元格数量
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
// 返回单元格内容
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
-> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath)
cell.textLabel?.text = "菜单\(indexPath.row + 1)"
return cell
}
}
2,侧栏菜单的使用
(1)主视图控制器中我们创建一个按钮,并在其点击响应中显示侧栏菜单。
import UIKit
import SideMenu
// 主视图控制器
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 创建一个按钮(点击后显示侧栏菜单)
let button = UIButton(type:.system)
button.frame = CGRect(x:40, y:100, width:150, height:30)
button.setTitle("打开侧栏菜单", for:.normal)
button.addTarget(self, action:#selector(tapped), for:.touchUpInside)
self.view.addSubview(button)
// 定义一个侧栏菜单
let menu = UISideMenuNavigationController(rootViewController: MenuViewController())
menu.isNavigationBarHidden = true //侧栏菜单不显示导航栏
// 将其作为默认的右侧菜单
SideMenuManager.default.menuLeftNavigationController = menu
}
// 按钮点击响应
@objc func tapped(){
// 显示侧栏菜单
self.present(SideMenuManager.default.menuLeftNavigationController!, animated: true,
completion: nil)
}
}
(2)运行结果如下:
- 点击“打开侧栏菜单”按钮后,主视图会向右滑动,露出下方的侧栏菜单。
- 侧栏菜单显示后,再次点击主视图(或者向左滑动屏幕)则会收起侧栏菜单。
- 侧栏菜单无论是展开还是收起过程中,都会有动画效果。

3,使用右侧菜单
(1)如果想要实现右侧栏菜单,使用时只需做如下修改:
import UIKit
import SideMenu
// 主视图控制器
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 创建一个按钮(点击后显示侧栏菜单)
let button = UIButton(type:.system)
button.frame = CGRect(x:40, y:100, width:150, height:30)
button.setTitle("打开侧栏菜单", for:.normal)
button.addTarget(self, action:#selector(tapped), for:.touchUpInside)
self.view.addSubview(button)
// 定义一个侧栏菜单
let menu = UISideMenuNavigationController(rootViewController: MenuViewController())
menu.isNavigationBarHidden = true //侧栏菜单不显示导航栏
// 将其作为默认的右侧菜单
SideMenuManager.default.menuRightNavigationController = menu
}
// 按钮点击响应
@objc func tapped(){
// 显示侧栏菜单
self.present(SideMenuManager.default.menuRightNavigationController!, animated: true,
completion: nil)
}
}
(2)运行结果如下:

4,关闭侧栏菜单
如果想通过代码来关闭侧栏菜单,可以使用如下代码。
self.dismiss(animated: true, completion: nil)
全部评论(0)