Нажмите ViewController справа налево с помощью UINavigationController - PullRequest
35 голосов
/ 10 марта 2010

Как все знают, UINavigationController выдвигает ViewController слева направо, есть ли способ сдвинуть представление справа налево?как анимация для кнопки назад.
На данный момент у меня есть это:


[self.navigationController pushViewController:viewController animated:YES];

Ответы [ 10 ]

52 голосов
/ 10 марта 2010

Вы можете создать NSMutableArray из массива navigationController viewcontrollers и вставить новый viewController перед текущим. Затем установите массив viewControllers без анимации и вернитесь назад.

UIViewController *newVC = ...;
NSMutableArray *vcs =  [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
[vcs insertObject:newVC atIndex:[vcs count]-1];
[self.navigationController setViewControllers:vcs animated:NO];
[self.navigationController popViewControllerAnimated:YES];
36 голосов
/ 15 ноября 2012

Пожалуйста, попробуйте это

HomePageController  *pageView = [[HomePageController alloc] initWithNibName:@"HomePageController_iPhone" bundle:nil];

CATransition *transition = [CATransition animation];
transition.duration = 0.45;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
transition.type = kCATransitionPush;
transition.subtype = kCATransitionFromLeft;
transition.delegate = self;
[self.navigationController.view.layer addAnimation:transition forKey:nil];

self.navigationController.navigationBarHidden = NO;
[self.navigationController pushViewController:pageView animated:NO];
9 голосов
/ 14 мая 2013
Try this :  
//Push effect in reverse way
    CATransition* transition = [CATransition animation];
    transition.duration = 0.75;
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromLeft;
    [self.navigationController.view.layer addAnimation:transition forKey:kCATransition];
    [self.navigationController pushViewController:vc animated:NO];
6 голосов
/ 05 мая 2013

Этот код работает нормально. Пожалуйста, попробуйте

CATransition *transition = [CATransition animation];
transition.duration = 0.3f;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionReveal;
[self.navigationController.view.layer addAnimation:transition forKey:nil];
[self.navigationController pushViewController:phoneServicesViewController animated:NO];
2 голосов
/ 08 сентября 2017

Основываясь на ответе @felixlam, я обновил и создал контроллер навигации в обратном направлении, который переопределяет методы push / pop по умолчанию, действуя следующим образом.

class LeftPushNavigationController: BaseNavigationController {

  override func viewDidLoad() {
    super.viewDidLoad()
    interactivePopGestureRecognizer?.isEnabled = false
  }

  override func pushViewController(_ viewController: UIViewController, animated: Bool) {
    // If the push is not animated, simply pass to parent
    guard animated else { return super.pushViewController(viewController, animated: animated) }

    // Setup back button
    do {
      // Hide original back button
      viewController.navigationItem.setHidesBackButton(true, animated: false)
      // Add new one
      viewController.navigationItem.rightBarButtonItem = UIBarButtonItem(
        image: #imageLiteral(resourceName: "iconBackReverse"),
        style: .plain,
        target: self,
        action: #selector(self.pop)
      )
    }

    // Calculate final order
    let finalVCs = self.viewControllers + [viewController]

    // Insert the viewController to the before-last position (so it can be popped to)
    var viewControllers = self.viewControllers
    viewControllers.insert(viewController, at: viewControllers.count - 1)

    // Insert viewcontroller before the last one without animation
    super.setViewControllers(viewControllers, animated: false)
    // Pop with the animation
    super.popViewController(animated: animated)
    // Set the right order without animation
    super.setViewControllers(finalVCs, animated: false)
  }

  override func popViewController(animated: Bool) -> UIViewController? {
    // If the push is not animated, simply pass to parent
    guard animated else { return super.popViewController(animated: animated) }

    guard self.viewControllers.count > 1 else { return nil }

    // Calculate final order
    var finalVCs = self.viewControllers
    let viewController = finalVCs.removeLast()

    // Remove the parent ViewController (so it can be pushed)
    var viewControllers = self.viewControllers
    let parentVC = viewControllers.remove(at: viewControllers.count - 2)

    // Set the viewcontrollers without the parent & without animation
    super.setViewControllers(viewControllers, animated: false)
    // Create push animation with the parent
    super.pushViewController(parentVC, animated: animated)
    // Set the right final order without animation
    super.setViewControllers(finalVCs, animated: false)

    // Return removed viewController
    return viewController
  }

  @objc
  private func pop() {
    _ = popViewController(animated: true)
  }

}
2 голосов
/ 05 августа 2015

Просто улучшение лучшего ответа здесь, на мой взгляд:

UIViewController *newVC = ...;
[self.navigationController setViewControllers:@[newVC, self] animated:NO];
[self.navigationController popViewControllerAnimated:YES];

А чтобы вернуться к первоначальному контроллеру, просто нажмите на него.

2 голосов
/ 10 марта 2010

Кажется, вы хотите «всплыть». Это может быть достигнуто тремя способами на вашем экземпляре UINavigationController:

Чтобы вернуться к «корневому» контроллеру:

-(NSArray *)popToRootViewControllerAnimated:(BOOL)animated

Или вернуться к одному из предыдущих контроллеров:

-(NSArray *)popToViewController:(UIViewController *)viewController animated:(BOOL)animated

Или вернуться к ранее нажатому контроллеру:

-(UIViewController *)popViewControllerAnimated:(BOOL)animated

2 голосов
/ 10 марта 2010

Нет, справа налево зарезервировано для выталкивания контроллеров представления из стека навигации.Однако вы можете получить такой эффект, анимируя взгляды самостоятельно.Что-то вроде:

[UIView beginAnimations:@"rightToLeft" context:NULL];
CGRect newFrame = aView.frame;
newFrame.origin.x -= newFrame.size.width;
aView.frame = newFrame;
[UIView commitAnimations];

Это, однако, не повлияет на ваш контроллер навигации.

0 голосов
/ 08 апреля 2019

Swift 5.0

 let pageView = TaskFolderListViewController.init(nibName: "HomePageController_iPhone", bundle: nil)
 let transition = CATransition()
 transition.duration = 0.45
 transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default)
 transition.type = CATransitionType.push
 transition.subtype = CATransitionSubtype.fromLeft
 self.navigationController?.view.layer.add(transition, forKey: kCATransition)
 self.navigationController?.pushViewController(pageView, animated: false)
0 голосов
/ 11 сентября 2014

У меня была такая же проблема, вот как я ее решил

[self.navigationController popViewControllerAnimated: YES];

Это будет напоминать «возвращение», т. Е. В ситуации, когда нажимается кнопка «Назад», и вы переходите на предыдущую страницу

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...