2015-05-24 2 views
0

Я хочу вернуться обратно от второго контроллера к первому, без использования SEGUE, но вместо этого я @IBAction подключен к моей задней кнопке, ниже код этого метода:Перемещения между контроллерами с TransitionManager

let deviceStoryboard = UIStoryboard(name: "Storyboard", bundle: nil) 
let deviceDashView = deviceStoryboard.instantiateViewControllerWithIdentifier("FirstView") as! 
self.navigationController!.transitioningDelegate = self.transitionManager 
self.navigationController!.pushViewController(deviceDashView, animated: true) 

As вы можете видеть, что я пытаюсь прикрепить свой собственный TransitionManager. Я создал его, потому что хочу иметь переходную анимацию, как «слева направо», и по умолчанию это наоборот.

Я знаю, как прикрепить свой TransitionManager, если я меняю вид с помощью segue, но пробовал различную конфигурацию для navigation controller, и ни один из них не работает.

Где я могу сделать ошибку?

ответ

0

Это немного больше затруднит, то, что вам нужно сначала, чтобы захватить ViewController вы хотите непосредственно перейти к и установки, как это, когда кнопка мыши:

var presenterStoryBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil) 
if let vc = presenterStoryBoard.instantiateViewControllerWithIdentifier("LoginViewController") as? LoginViewController 
{ 
    self.isPresenting = false //this flag helps to find the end of the transition 
    vc.modalPresentationStyle = .Custom 
    vc.transitioningDelegate = self 
    self.presentViewController(vc , animated: true) 
    { 
     self.isPresenting = false 
    } 
} 

После этого вам нужно будет создать класс отвечает за анимацию, этот класс реализует UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate и имеет методы первой необходимости для перехода:

class TransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { 

func animateTransition(transitionContext: UIViewControllerContextTransitioning) { 

     // get reference to our fromView, toView and the container view that we should perform the transition in 
     let container = transitionContext.containerView() 
     let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! 
     let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! 

     UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: nil, animations: { 
       //Create your animation here 
      }, completion: { 
       finished in 
       transitionContext.completeTransition(true) 
     }) 
} 

// return how many seconds the transition animation will take 
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { 
     return 0.5 
} 

// return the animataor when presenting a viewcontroller 
// remmeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol 
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { 
     return self 
} 

// return the animator used when dismissing from a viewcontroller 
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { 
     return self 
    } 
} 

Помните, что взгляды от и зависеть в направлении вы собираетесь, от Мастера к деталям из является Учителем это det Айыл, однако, когда вы закроете деталь будет инвертировать и от будет подробно и в будет Master

+0

это правильно ?: vc.transitioningDelegate = само не должна быть ссылка на мой TransitionManager ? – shtas

+0

Нет, пример верен, TransactionManager реализует UIViewControllerTransitioningDelegate, а контроллер представления, выполняющий переход, должен установить этот делегат сам по себе, как в примере. Я просто копирую и прошёл здесь из рабочей формы входа в один из моих приложений. – Icaro

+0

Когда я устанавливаю ее самостоятельно, я получаю сообщение об ошибке в строке с vc.transitioningDelegate = self: Невозможно присвоить значение типа ' MyControllerWithButton 'для значения типа' UIViewControllerTransitioningDelegate? ' Кроме того, где я должен помещать этот флаг «isPresenting» в мой класс Controller или TransitionManager? – shtas

Смежные вопросы