水平滑动以关闭 swift 中的视图控制器

Swipe horizontally to dismiss a view controller in swift

我有一个显示为弹出窗口的视图控制器,我将它显示在另一个视图控制器中。当我滑动 left/right 关闭时,我想要这个视图控制器。我该怎么做?

我的视图控制器:

import UIKit

class DelayAlertViewController: UIViewController {
        

    @IBOutlet var contentView: UIView!
    @IBOutlet weak var viewShadow: UIView!
    @IBOutlet weak var delayAlertView: DelayAlertView!
    @IBOutlet weak var infoImage: UIImageView!
    @IBOutlet weak var bannerLabel: UILabel!
    
    private var message: String

    
    init(with message: String) {
        self.message = message
        super.init(nibName: "DelayAlertViewController", bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .clear
        self.modalPresentationStyle = .overCurrentContext
        self.definesPresentationContext = false
        self.delayAlertView.layer.borderWidth = 0.2
        self.delayAlertView.layer.borderColor = UIColor.black.cgColor
        self.viewShadow.addRoundedCornersShadow(radius: 1, width: 0, height: 0, opacity: 0.2)
        delayAlertView.layer.masksToBounds = false
        delayAlertView.layer.cornerRadius = 5
        delayAlertView.clipsToBounds = true
    }
    
 
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
}

如果我理解正确你的问题,在 viewDidLoad 中添加:

override func viewDidLoad() {
    super.viewDidLoad()
    ...
    setupGestureRecognizers()
}

然后:

private func setupGestureRecognizers() {
    let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeAction(swipe:)))
    leftSwipe.direction = UISwipeGestureRecognizer.Direction.left
    view.addGestureRecognizer(leftSwipe)
}

最后 target-action:

@objc func swipeAction(swipe: UISwipeGestureRecognizer) {
    self.dismiss(animated: true)
}

更新: 如果您想要自定义关闭动画,例如向左或向右,请在 swipeAction:

中尝试此代码
@objc func swipeAction(swipe: UISwipeGestureRecognizer) {
   let transition = CATransition()
   transition.duration = 0.5
   transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
   transition.type = CATransitionType.push
   transition.subtype = CATransitionSubtype.fromRight
   self.view.window!.layer.add(transition, forKey: nil)
   self.dismiss(animated: false, completion: nil)
}