从右/左动画presentModalViewController

时间:2012-01-25 08:55:58

标签: iphone objective-c animation presentmodalviewcontroller

目前我正在使用[self presentModalViewController :newVC animated:YES]。我想通过推送效果从左/右/上/下呈现newViewcontroller。我尝试使用CATransition但它在转换之间显示黑屏。

6 个答案:

答案 0 :(得分:91)

出席时:

CATransition *transition = [CATransition animation];
transition.duration = 0.3;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromRight;
[self.view.window.layer addAnimation:transition forKey:nil];

[self presentModalViewController:viewCtrl animated:NO];

解雇时:

CATransition *transition = [CATransition animation];
transition.duration = 0.3;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromLeft;
[self.view.window.layer addAnimation:transition forKey:nil];
[self dismissModalViewControllerAnimated:NO];

答案 1 :(得分:3)

我遇到了同样的问题。假设您要从视图控制器1呈现视图控制器2.在第一个视图控制器中使用

 [self presentModalViewController: controller animated: NO]];

在第二个视图控制器中,在viewWillAppear:方法中添加代码

    CATransition *animation = [CATransition animation];

    [animation setDelegate:self];
    [animation setType:kCATransitionPush];
    [animation setSubtype:kCATransitionFromRight];

    [animation setDuration:0.40];
    [animation setTimingFunction:
     [CAMediaTimingFunction functionWithName:
      kCAMediaTimingFunctionEaseInEaseOut]];


    [self.view.layer addAnimation:animation forKey:kCATransition];

它会正常工作。如果再次出现黑屏,如果您使用的是导航控制器,请更换

   [self.view.layer addAnimation:animation forKey:kCATransition];

   [self.navigationController.view.layer addAnimation:animation forKey:kCATransition];

答案 2 :(得分:2)

在X> = 4小时的工作之后,这可以在没有"撕裂"或其他背景文物:

class AboutTransition: NSObject, UIViewControllerAnimatedTransitioning {

    let presenting: Bool
    let duration: NSTimeInterval

    init(presenting: Bool, duration: NSTimeInterval = 0.25) {
        self.presenting = presenting
        self.duration = duration
    }

    @objc func transitionDuration(ctx: UIViewControllerContextTransitioning) -> NSTimeInterval {
        return duration
    }

    @objc func animateTransition(ctx: UIViewControllerContextTransitioning) {
        let duration = transitionDuration(ctx)
        let containerView = ctx.containerView()
        let fromViewController = ctx.viewControllerForKey(UITransitionContextFromViewControllerKey)!
        let toViewController = ctx.viewControllerForKey(UITransitionContextToViewControllerKey)!
        let fromView = fromViewController.view // 7.0 & 8.0 compatible vs. viewForKey:
        let toView = toViewController.view     // 7.0 & 8.0 compatible vs. viewForKey:

        containerView.addSubview(fromView)
        containerView.addSubview(toView)

        let offScreenRight = CGAffineTransformMakeTranslation(containerView.frame.width, 0)
        let offScreenLeft = CGAffineTransformMakeTranslation(-containerView.frame.width, 0)

        fromView.transform = CGAffineTransformIdentity
        toView.transform = self.presenting ? offScreenRight : offScreenLeft

        UIView.animateWithDuration(duration, delay:0, options:UIViewAnimationOptions(0), animations: {
            fromView.transform = self.presenting ? offScreenLeft : offScreenRight
            toView.transform = CGAffineTransformIdentity

        }, completion: { (finished: Bool) in
            ctx.completeTransition(finished)
            if finished {
                fromView.removeFromSuperview()
                fromView.frame = toView.frame // reset the frame for reuse, otherwise frame transforms will accumulate
            }
        })
    }
}

然后在AppDelegate.swift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UINavigationControllerDelegate {

    lazy var window: UIWindow? = {
        return UIWindow(frame: UIScreen.mainScreen().bounds)
    }()

    lazy var storyboard = UIStoryboard(name: "Main", bundle: nil)

    lazy var nav: UINavigationController = {
        var r = self.storyboard.instantiateInitialViewController() as! UINavigationController
        r.delegate = self
        return r
    }()

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        self.window!.rootViewController = nav
        self.window!.makeKeyAndVisible()

        // .. other setup

        return true
    }

    // ...


    // MARK: - UINavigationControllerDelegate

    func navigationController(navigationController: UINavigationController, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController, toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        // Example of a SettingsViewController which pushes AboutViewController
        if fromVC is SettingsViewController && toVC is AboutViewController { // Push to About
            return AboutTransition(presenting: true)
        } else if fromVC is AboutViewController && toVC is SettingsViewController { // Pop to Settings
            return AboutTransition(presenting: false)
        }
        return nil
    }
}

这假定应用正在使用默认情节提要,初始VC为UINavigationController

更新swift 3/4

class LTRTransition: NSObject, UIViewControllerAnimatedTransitioning
{ 
let presenting: Bool
let duration: TimeInterval

init(presenting: Bool, duration: TimeInterval = Theme.currentTheme.animationDuration) {
    self.presenting = presenting
    self.duration = duration
}

@objc func transitionDuration(using ctx: UIViewControllerContextTransitioning?) -> TimeInterval {
    return duration
}

@objc func animateTransition(using ctx: UIViewControllerContextTransitioning) {
    let duration = transitionDuration(using: ctx)
    let containerView = ctx.containerView
    let fromViewController = ctx.viewController(forKey: UITransitionContextViewControllerKey.from)!
    let toViewController = ctx.viewController(forKey: UITransitionContextViewControllerKey.to)!
    guard let fromView = fromViewController.view, // 7.0 & 8.0 compatible vs. viewForKey:
        let toView = toViewController.view     // 7.0 & 8.0 compatible vs. viewForKey:
        else {
            assertionFailure("fix this")
            return
    }
    containerView.addSubview(fromView)
    containerView.addSubview(toView)

    let offScreenRight = CGAffineTransform(translationX: containerView.frame.width, y: 0)
    let offScreenLeft = CGAffineTransform(translationX: -containerView.frame.width, y: 0)

    fromView.transform = CGAffineTransform.identity
    toView.transform = self.presenting ? offScreenRight : offScreenLeft

    UIView.animate(withDuration: duration, delay:0, options:UIViewAnimationOptions(rawValue: 0), animations: {
        fromView.transform = self.presenting ? offScreenLeft : offScreenRight
        toView.transform = CGAffineTransform.identity

    }, completion: { (finished: Bool) in
        ctx.completeTransition(finished)
        if finished {
            fromView.removeFromSuperview()
             // this screws up dismissal. at least on ios10 it does               fromView.frame = toView.frame // reset the frame for reuse, otherwise frame transforms will accumulate
        }
    })
}
}

VC的transitioniningDelegate实现被推/解:

extension WhateverVCyouArePresentingFrom: UIViewControllerTransitioningDelegate
{
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
    return LTRTransition(presenting: true)
}

public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?
{
    return LTRTransition(presenting: false)
}
}

答案 3 :(得分:1)

这看起来很棘手,但是只需几行代码即可完成。

首先,以模态形式显示LeftSlideViewController。您需要为.overCurrentContext指定modalPresentationStyle。

if let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LeftSlideViewController") as? LeftSlideViewController {
         vc.modalPresentationStyle = .overCurrentContext
        self.present(vc, animated: false, completion: nil)
    }

然后,打开LeftSlideViewController。

要从左侧移入(使用CATransition)

  • 在loadView中隐藏视图。

    self.view.isHidden = true
    
  • 在viewDidAppear中的视图中添加向左移动的过渡动画

    self.view.isHidden = false
    
    let transition = CATransition.init()
    transition.duration = 0.3
    transition.timingFunction = CAMediaTimingFunction.init(name: .easeInEaseOut)
    transition.type = .moveIn
    transition.subtype = .fromLeft
    
    self.view.layer.add(transition, forKey: nil)
    

向左移(使用UIView动画)

  • 使用UIView动画对视图的框架进行动画处理,并在动画完成后关闭ViewController

    UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: {
        self.view.frame = CGRect(x: self.view.frame.width * -1, y: 0, width: self.view.frame.width, height: self.view.frame.height)
    }) { (finished) in
        self.dismiss(animated: false, completion: nil)
    }
    

答案 4 :(得分:0)

只有四个UIModalTransitionStyles:

UIModalTransitionStyleCoverVertical
UIModalTransitionStyleFlipHorizontal
UIModalTransitionStyleCrossDissolve
UIModalTransitionStylePartialCurl

例如:

UIViewController *controller = [[[MyViewController alloc] init] autorelease];
UIModalTransitionStyle trans = UIModalTransitionStyleFlipHorizontal;
[UIView beginAnimations: nil context: nil];
[UIView setAnimationTransition: trans forView: [self window] cache: YES];
[navController presentModalViewController: controller animated: NO];
[UIView commitAnimations];

答案 5 :(得分:-1)

您可以在视图控制器上设置要显示的transitioningDelegate。您必须符合UIViewControllerTransitioningDelegateUIViewControllerAnimatedTransitioning协议。通过实现animateTransition(transitionContext: UIViewControllerContextTransitioning),您可以为视图控制器子视图设置动画。

执行转换的功能

class fromViewController : UIViewController {
    let transitionManager = TransitionManager()

    func transitionToViewController() {
      toController.transitioningDelegate = transitionManager
      presentViewController(toController, animated: true, completion: nil)
    }
}

然后TransitionManager看起来像:

import UIKit

class TransitionManager : UIPercentDrivenInteractiveTransition {
    var presenting = false
}

// MARK: UIViewControllerAnimatedTransitioning
extension TransitionManager : UIViewControllerAnimatedTransitioning {
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        let container = transitionContext.containerView()
        let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
        let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!

        let offScreenRight = CGAffineTransformMakeTranslation(container.frame.width, 0)
        let offScreenLeft = CGAffineTransformMakeTranslation(-container.frame.width, 0)

        toView.transform = self.presenting ? offScreenRight : offScreenLeft

        container.addSubview(toView)
        container.addSubview(fromView)
        let duration = self.transitionDuration(transitionContext)

        UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 1, initialSpringVelocity: 0.8, options: nil, animations: {
          fromView.transform = self.presenting ? offScreenLeft : offScreenRight
          toView.transform = CGAffineTransformIdentity

          }, completion: { finished in
            transitionContext.completeTransition(true)
        })
    }


    func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
        return 0.3
    }
}


// MARK: UIViewControllerTransitioningDelegate
extension TransitionManager : UIViewControllerTransitioningDelegate {
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.presenting = true
        return self
    }

    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.presenting = false
        return self
    }
}