Replace view with animation in Swift

1.3k Views Asked by At

I have a 2 NSSplitView on the main window: enter image description here

For the first NSSplitView I wanted to replace the subview[0] with another NSView with different color. The transition should be from Right/Left/Top/Bottom. I tried changing the transition.duration and transition.type to different values, but changing those values have no effect on view transition!

class ViewController: NSViewController {
    @IBOutlet weak var splitView1: CustomSplitView!
    @IBOutlet weak var splitView2: CustomSplitView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.wantsLayer = true
        self.splitView1.wantsLayer = true
        self.splitView2.wantsLayer = true
        self.view.canDrawSubviewsIntoLayer = true
        self.splitView1.canDrawSubviewsIntoLayer = true
        self.splitView2.canDrawSubviewsIntoLayer = true
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) { // Change after 2 seconds
            self.presentViewWithAnimation()
        }
    }   
    func presentViewWithAnimation() {
        let sourceView = self.splitView1.subviews[0]
        self.splitView1.animations = [NSAnimatablePropertyKey(rawValue: "subviews"): self.slideAnimation()!]
        let frame: NSRect = sourceView.visibleRect
        let newView: NSView = NSView(frame: frame)
        newView.wantsLayer = true
        newView.layer?.backgroundColor = NSColor.darkGray.cgColor
        NSAnimationContext.current.duration = 15 // tried adding this, does not work
        self.splitView1.replaceSubview(sourceView, with: newView)
    }
    func slideAnimation() -> CATransition? {
        let transition = CATransition()
        transition.type = kCATransitionPush
        transition.duration = 100 // duration does not work
        transition.speed = 0.5
        transition.subtype = kCATransitionFromRight
        return transition
    }
}

Related to How to make an slide animation while bringing an custom view in Cocoa?

1

There are 1 best solutions below

0
Marc T. On

With NSViewController you can use

func transition(from fromViewController: NSViewController, 
to toViewController: NSViewController, 
options: NSViewController.
TransitionOptions = [], 
completionHandler completion: (() -> Void)? = nil)

to animate the replacement of the views. I have seen that there is already an instruction how to do so but if you have further questions I will try to help.