In iOS, how to drag down to dismiss a modal?

后端 未结 15 2359
粉色の甜心
粉色の甜心 2020-11-28 00:41

A common way to dismiss a modal is to swipe down - How do we allows the user to drag the modal down, if it\'s far enough, the modal\'s dismissed, otherwise it animates back

15条回答
  •  一向
    一向 (楼主)
    2020-11-28 00:48

    Only vertical dismiss

    func panGestureAction(_ panGesture: UIPanGestureRecognizer) {
        let translation = panGesture.translation(in: view)
    
        if panGesture.state == .began {
            originalPosition = view.center
            currentPositionTouched = panGesture.location(in: view)    
        } else if panGesture.state == .changed {
            view.frame.origin = CGPoint(
                x:  view.frame.origin.x,
                y:  view.frame.origin.y + translation.y
            )
            panGesture.setTranslation(CGPoint.zero, in: self.view)
        } else if panGesture.state == .ended {
            let velocity = panGesture.velocity(in: view)
            if velocity.y >= 150 {
                UIView.animate(withDuration: 0.2
                    , animations: {
                        self.view.frame.origin = CGPoint(
                            x: self.view.frame.origin.x,
                            y: self.view.frame.size.height
                        )
                }, completion: { (isCompleted) in
                    if isCompleted {
                        self.dismiss(animated: false, completion: nil)
                    }
                })
            } else {
                UIView.animate(withDuration: 0.2, animations: {
                    self.view.center = self.originalPosition!
                })
            }
        }
    

提交回复
热议问题