swift中仿QQ侧滑的思路
首先说明一下相关类文件,如下图
思路步骤如下:
- 在AppDelegate中,指定window的rootViewController为RootViewController
- 在RootViewController中创建UINavigationController为mainNav,将MainViewController作为mainNav的rootViewController,创建menuVC:MenuViewController,将mainNav.view和menuVC.view都加载在RootViewController的view上,menuVC.view的图层关系在mainNav.view之下
相关代码如下
// 在AppDelegate中
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = RootViewController()
self.window?.makeKeyAndVisible()
return true
}
// 在RootViewController中
import UIKit
// 枚举
enum MenuState {
case Collapsed // 未显示(收起)
case Expanding // 展开中
case Expanded // 展开
}
class RootViewController: UIViewController {
// 主页导航控制器
var mainNav: UINavigationController?
// 主页控制器
var mainVC: MainViewController!
// 菜单页控制器
var menuVC: MenuViewController?
// 菜单当前状态
var currentState = MenuState.Collapsed {
/**
didSet方法:在新的值被设定后立即调用。
在初始化的时候赋值,是不调用didSet方法的。
*/
didSet {
let shouldShowShadow = currentState != .Collapsed
showShadowForMainViewController(shouldShowShadow)
}
}
// 菜单打开后主页在屏幕右侧露出部分的宽度
let menuViewExpandedOffset:CGFloat = 60.0
// 侧滑菜单黑色半透明遮罩层
var blackCover: UIView?
// 最小缩放比例
let minProportion: CGFloat = 0.8
// MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
// 初始化主视图
let main = MainViewController()
self.mainNav = UINavigationController(rootViewController: main)
self.view.addSubview((self.mainNav?.view)!)
// 创建mainVC控制器
mainVC = mainNav!.viewControllers.first as! MainViewController!
// 添加leftBarButtonItem
let leftItemBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
let btnImage = UIImage(named: "icon.jpg")
leftItemBtn.setBackgroundImage(btnImage, for: .normal)
leftItemBtn.layer.masksToBounds = true
leftItemBtn.layer.cornerRadius = leftItemBtn.frame.height / 2
leftItemBtn.addTarget(self, action: #selector(showMenu), for: .touchUpInside)
let leftBarButtonItem = UIBarButtonItem(customView: leftItemBtn)
self.mainVC?.navigationItem.leftBarButtonItem = leftBarButtonItem
// 添加拖动手势
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
self.mainNav?.view.addGestureRecognizer(panGestureRecognizer)
// 单击收起菜单手势
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapGestureRecognizerClick))
self.mainNav?.view.addGestureRecognizer(tapGestureRecognizer)
}
// 单击收起菜单手势响应
func tapGestureRecognizerClick() {
// 如果菜单是展开的点击主页部分则会收起
if currentState == .Expanded {
animateMainView(false)
}
}
// 拖动手势响应
func handlePanGesture(_ recognizer: UIPanGestureRecognizer) {
switch recognizer.state {
case .began:
// 刚刚开始滑动
// 判断拖动的方向
let dragFromLeftToRight = recognizer.velocity(in: view).x > 0
// 如果刚刚开始滑动的时候还处于主页面,从左向右滑动加入侧面菜单
if currentState == .Collapsed && dragFromLeftToRight {
currentState = .Expanding
// 添加菜单控制器
addMenuViewController()
}
case .changed:
// 正在滑动,则偏移主视图的坐标实现跟随手指位置移动
let screenWidth = self.view.bounds.size.width
var centerX = recognizer.view!.center.x + recognizer.translation(in: view).x
// 页面滑动到最左侧的话就不许继续往左移动
if centerX < screenWidth/2 {
centerX = screenWidth/2
}
// 计算缩放比例
var proportion:CGFloat = (centerX - screenWidth/2) / (self.view.bounds.width - menuViewExpandedOffset)
proportion = 1 - (1 - minProportion) * proportion
// 执行视差特效
blackCover?.alpha = (proportion - minProportion) / (1 - minProportion)
// 主页面滑到最左侧的话就不许继续往左移动
recognizer.view?.center.x = centerX
// 拖拽的动画效果
recognizer.setTranslation(CGPoint.zero, in: view)
// 缩放主页面
recognizer.view!.transform =
CGAffineTransform.init(scaleX: proportion, y: proportion)
case .ended:
// 滑动结束,根据滑动是否过半,判断后面时自动展开还是收缩
let hasMovedhanHalfway = (recognizer.view?.center.x)! > view.bounds.width
animateMainView(hasMovedhanHalfway)
default:
break
}
}
// 显示菜单
func showMenu() {
// 如果菜单是展开的则会收起,否则就展开
if currentState == .Expanded {
animateMainView(false)
}
else {
addMenuViewController()
animateMainView(true)
}
}
// 添加菜单控制器
func addMenuViewController() {
if menuVC == nil {
menuVC = MenuViewController()
// 插入当前视图并置顶
self.view.insertSubview(menuVC!.view, belowSubview: (self.mainNav?.view)!)
// 在侧滑菜单之上增加黑色遮罩层,目的是实现视差特效
// blackCover = UIView(frame: self.view.frame)
// 和上面一种写法创建UIView一样。注:offsetBy:宽高与父视图一样,只是设置x,y在父视图的偏移量
blackCover = UIView(frame: self.view.frame.offsetBy(dx: 0, dy: 0))
blackCover!.backgroundColor = UIColor.black
self.view.insertSubview(blackCover!, belowSubview: (self.mainNav?.view)!)
}
}
// 执行动画效果
func animateMainView(_ shouldExpand: Bool) {
if shouldExpand {
// 更新当前状态
currentState = .Expanded
// 动画
let mainPosition = view.bounds.size.width * (1 + minProportion / 2) - menuViewExpandedOffset
doTheAnimate(mainPosition: mainPosition, mainProPortion: minProportion, blackCoverAlpha: 0)
}
else {
doTheAnimate(mainPosition: view.bounds.width/2, mainProPortion: 1, blackCoverAlpha: 1, completion: { (finished) in
// 动画结束之后更新状态
self.currentState = .Collapsed
// 移除左侧视图
self.menuVC?.view.removeFromSuperview()
// 释放内存
self.menuVC = nil
// 移除黑色遮罩层
self.blackCover?.removeFromSuperview()
// 释放内存
self.blackCover = nil
})
}
}
// 主页移动动画,黑色遮罩层动画
func doTheAnimate(mainPosition: CGFloat, mainProPortion: CGFloat, blackCoverAlpha: CGFloat, completion: ((Bool) -> Void)! = nil) {
// usingSpringWithDamping: 若设置为1.0则没有弹簧效果
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .curveEaseOut, animations: {
self.mainNav?.view.center.x = mainPosition
self.blackCover?.alpha = blackCoverAlpha
// 缩放主页面
self.mainNav?.view.transform = CGAffineTransform(scaleX: mainProPortion, y: mainProPortion)
}, completion: completion)
}
// 给主页面边缘添加、取消阴影
func showShadowForMainViewController(_ shouldShowShadow: Bool) {
if shouldShowShadow {
// 需要遮挡不透明度为0.8
self.mainNav?.view.layer.shadowOpacity = 0.8
}
else {
self.mainNav?.view.layer.shadowOpacity = 0.0
}
}
}
// 在MenuViewController中
import UIKit
class MenuViewController: UIViewController {
let titlesArray = ["开通会员", "QQ钱包", "网上营业厅", "个性打扮", "我的收藏", "我的相册"]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.red
self.setupUI()
}
func setupUI() {
// 头像
let iconImageView = UIImageView(frame: CGRect(x: 10, y: 64+10, width: 60, height: 60))
iconImageView.image = UIImage(named: "icon.jpg")
self.view.addSubview(iconImageView)
// 姓名
let nameLabel = UILabel(frame: CGRect(x: iconImageView.frame.maxX+10, y: iconImageView.frame.origin.y, width: 100, height: 30))
nameLabel.text = "不安分心"
self.view.addSubview(nameLabel)
// star
let starImageView = UIImageView(frame: CGRect(x: nameLabel.frame.origin.x, y: nameLabel.frame.maxY, width: 100, height: 30))
starImageView.backgroundColor = UIColor.yellow
self.view.addSubview(starImageView)
// intrude
let intrudeLabel = UILabel(frame: CGRect(x: iconImageView.frame.origin.x, y: iconImageView.frame.maxY+10, width: 260, height: 30))
intrudeLabel.font = UIFont.systemFont(ofSize: 13)
intrudeLabel.text = "当野心支撑不起梦想,那就狠狠地学习"
self.view.addSubview(intrudeLabel)
let tableHeight = UIScreen.main.bounds.height-iconImageView.frame.maxY
let tableViewFrame = CGRect(x: iconImageView.frame.origin.x, y: intrudeLabel.frame.maxY+10, width: 300, height: tableHeight)
let tableView = UITableView(frame: tableViewFrame, style: .plain)
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
tableView.backgroundColor = UIColor.clear
// 去除所有cell的分割线
tableView.separatorStyle = .none
self.view.addSubview(tableView)
}
}
extension MenuViewController: UITableViewDelegate, UITableViewDataSource {
// UITableViewDataSource方法,可选
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// UITableViewDataSource方法,必选
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titlesArray.count
}
// UITableViewDataSource方法,必选
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.imageView?.image = UIImage(named: "icon.jpg")
cell.backgroundColor = UIColor.clear
cell.textLabel?.text = titlesArray[indexPath.row]
cell.textLabel?.textColor = UIColor.white
return cell
}
// UITableViewDelegate方法,可选
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
print("开通会员")
}
else if (indexPath.row == 1){
print("QQ钱包")
}
else if (indexPath.row == 2){
print("网上营业厅")
}
else if (indexPath.row == 3){
print("个性打扮")
}
else if (indexPath.row == 4){
print("我的收藏")
}
else if (indexPath.row == 5){
print("我的相册")
}
}
}
// 在MainViewController中
import UIKit
class MainViewController: UIViewController {
var searchBar: UISearchBar?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.setupNav()
self.setupSearchBar()
}
func setupSearchBar() {
// 创建UISearchBar
let searchBar = UISearchBar(frame: CGRect(x: 20, y: 64+10, width: UIScreen.main.bounds.width-2*20, height: 50))
searchBar.searchBarStyle = .minimal
searchBar.placeholder = "搜索"
searchBar.delegate = self
self.view.addSubview(searchBar)
self.searchBar = searchBar
}
func setupNav() {
// 创建UISegmentedControl
let items = ["消息", "电话"]
let segmentedControl = UISegmentedControl(items: items)
// 设置默认选中
segmentedControl.selectedSegmentIndex = 0
// 设置点击事件
segmentedControl.addTarget(self, action: #selector(segmentedControlClick(_ :)), for: .valueChanged)
self.navigationItem.titleView = segmentedControl
}
func segmentedControlClick(_ segmentedControl: UISegmentedControl) {
if segmentedControl.selectedSegmentIndex == 0 {
print("选中了消息")
}
else {
print("选中了电话")
}
}
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
self.searchBar?.resignFirstResponder()
}
}
extension MainViewController: UISearchBarDelegate {
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
print("搜索条件:\(searchBar.text)")
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
}