Swift - 第三方侧栏菜单组件SideMenu使用详解2(Storyboard定义菜单+代码调用)
作者:hangge | 2019-03-18 08:10
三、Storyboard 定义菜单 + 代码调用菜单
1,侧栏菜单的定义
(1)首先在 Storyboard 中拖入一个 Navigation Controller 用于放置(或者说作为)侧栏菜单。

(2)将 TableView 里的单元格设置为静态单元格,并添加一些内容作为菜单栏项。

(3)选中这个 Navigation Controller 并做如下设置:
- 将 Class 设置为 UISideMenuNavigationController
- 将 Module 设置为 SideMenu
- 将 Storyboard ID 设置为 LeftMenu

(4)由于这个侧栏菜单不需要导航栏,我们把这个侧栏菜单 Navigation Controller 的 Shows Navigation Bar 勾选取消掉。

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) // 定义一个侧栏菜单(从Storyboard中获取) let menuLeftNavigationController = storyboard! .instantiateViewController(withIdentifier: "LeftMenu") as! UISideMenuNavigationController // 将其作为默认的左侧菜单 SideMenuManager.default.menuLeftNavigationController = menuLeftNavigationController } // 按钮点击响应 @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) // 定义一个侧栏菜单(从Storyboard中获取) let menuLeftNavigationController = storyboard! .instantiateViewController(withIdentifier: "LeftMenu") as! UISideMenuNavigationController // 将其作为默认的右侧菜单 SideMenuManager.default.menuRightNavigationController = menuLeftNavigationController } // 按钮点击响应 @objc func tapped(){ // 显示侧栏菜单 self.present(SideMenuManager.default.menuRightNavigationController!, animated: true, completion: nil) } }
(2)运行结果如下:



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