Search code examples
iosxcodeuiviewcontrollersegueuistoryboardsegue

Transition Screens from Left to Right?


I would like to create a segue. I am using Swift. I want the new View Controller to slide in from the left. This means that the previous View Controller will slide out from left to right. I have tried the segues Push, Replace, Present Modally, and Present as Popover but none of them do the left to right transition. They either have a right to left transition or the new screen appears from the bottom of the screen. How can I make a left to right transition? Thanks.


Solution

  • You could write a custom transition that would not be too difficult but if you don't want to go that route here is a simple fix that will work. Click on the segue and unclick/disable animates on the segue. Then in prepareForSegue use this.

      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if let _ = segue.destination as? NextViewController{
                let trans = CATransition()
                trans.type = kCATransitionMoveIn
                trans.subtype = kCATransitionFromLeft
                trans.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
                trans.duration = 0.35
                self.navigationController?.view.layer.add(trans, forKey: nil)
            }
        }
    

    Feel free to explore the other options with CATransition types. You can have some serious fun with them. Now I am guessing you want to have the reverse for the back button press in the next view controllers. You will have to replace the back button and to intercept the back press and pop without animation so you can add your own animation. Here is what that would look like.

     override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(backTapped))
    }
    
    @objc func backTapped() {
        let trans = CATransition()
        trans.type = kCATransitionMoveIn
        trans.subtype = kCATransitionFromRight
        trans.duration = 0.3
        self.navigationController?.view.layer.add(trans, forKey: nil)
        navigationController?.popViewController(animated: false)
    }
    

    Again the other option would be use UIViewControllerAnimatedTransitioning but depending on your skill level and comfort with animations I find the above an easy implementation.