手势

手势滑动返回

 

1.1实现向右滑动返回

1.1.1案例1:当使用UINavigationController的时候用pushViewController(_,animated:)

   ——返回之前的视图popViewController(animated:)

 

如图:

代码如下:

 pushViewController(_,animated:)

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //通过indexPath获取用户所单击的单元格的用户对象
        let cell = tableView.cellForRow(at: indexPath) as! FollowersCell
        
        //如果用户单击单元格,或者进入HomeVC或者进入GuestVC
        if cell.usernameLbl.text == AVUser.current()?.username {
            let home = storyboard?.instantiateViewController(withIdentifier: "HomeVC") as! HomeVC
            self.navigationController?.pushViewController(home, animated: true)
        }else {
            guestArray.append(followerArray[indexPath.row])
            let guest = storyboard?.instantiateViewController(withIdentifier: "GuestVC") as! GuestVC
            self.navigationController?.pushViewController(guest, animated: true)
        }
    }

 返回之前的视图popViewController(animated:)

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //允许垂直的拉拽刷新操作
        self.collectionView?.alwaysBounceVertical = true
        
        //导航栏的顶部信息
        self.navigationItem.title = guestArray.last?.username
        
        //定义导航栏中新的返回按钮
        self.navigationItem.hidesBackButton = true
        let backBtn = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(back(_:)))
        self.navigationItem.leftBarButtonItem = backBtn
        
        //实现向右划动返回
        let backSwipe = UISwipeGestureRecognizer(target: self, action: #selector(back(_:)))
        backSwipe.direction = .right
        self.view.addGestureRecognizer(backSwipe)
        

    }

 当单击返回按钮以后,需要执行back(_:)方法,所以在viewDidLoad()方法结束后我们定义了该方法。该方法有一个参数,会回传被单击的UI对象(UIBarButtonItem按钮),我们不会用到它,所以这里将其忽略。

完成back(_:)方法中的程序代码:

    func back(_:UIBarButtonItem){
        //退回到之前的控制器
        _ = self.navigationController?.popViewController(animated: true)
        }

Ps:在Xcode8中,若直接使用self.navigationController?.popViewController(animated:true)这句话会出现一条警告消息:Expression of type 'UIViewController?' is unused,意思是popViewController(animated:)方法有一个UIViewController类型的返回值,而这个返回值并没有被使用。解决这个问题,只需要将上面的这行代码修改为_ = self.navigationController?.popViewController(animated:true)即可,上面的_代表一个在之后绝不会用到的量。 

 

1.1.2其他使用使用模态弹出present(_,animated:)

   ———返回之前的视图使用dismiss(_,animated:)

 

1.1.3滑动内容学习扩展

1.Swift - 让导航栏随页面一起移动,而不是淡入淡出 http://www.hangge.com/blog/cache/detail_1117.html

2.Swift - 修改导航栏“返回”按钮文字,图标 http://www.hangge.com/blog/cache/detail_957.html

3.Swift - 自定义导航栏leftBarButtonItems导致滑动返回失效问题解决 http://www.hangge.com/blog/cache/detail_1092.html