I have a View Controller that appears as a pop up, that I presented it inside an other View Controller. I want this view controller when I swipe left/right to dismiss. How can I do this?
My View Controller:
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)
}
}
CodePudding user response:
If I understand correctly your question, in viewDidLoad add this:
override func viewDidLoad() {
super.viewDidLoad()
...
setupGestureRecognizers()
}
Then:
private func setupGestureRecognizers() {
let leftSwipe = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeAction(swipe:)))
leftSwipe.direction = UISwipeGestureRecognizer.Direction.left
view.addGestureRecognizer(leftSwipe)
}
And finally target-action:
@objc func swipeAction(swipe: UISwipeGestureRecognizer) {
self.dismiss(animated: true)
}
Update: If you want custom dismiss animation, for example left or right, try this code inside 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)
}