2016-06-12 10 views
10

Привет Я пытаюсь представить ViewController и отклонить мой текущий вид модального но этот код не работаетУволить и Present View Controller в Swift

self.dismissViewControllerAnimated(true, completion: { 
       let vc = self.storyboard?.instantiateViewControllerWithIdentifier("OrderViewController") 
       self.presentViewController(vc!, animated: true, completion: nil) 
      }) 

наоборот не работает тоже на завершение блока presentviewcontroller

EDIT: заменить vc! к себе

+0

попробовать с self.parentViewController .presentViewController (ЖЕЛ !, анимированные: true, complete: noil) –

+0

@SandeepKumar все еще не работает –

+0

Вы пытаетесь представить сначала или уволить сперва? – Code

ответ

14

Вы должны получить viewCont ролик, который представил сам (текущий ViewController). Если этот контроллер представлений является rootViewController, который можно использовать, как показано ниже, если не этот запрос, он основан на вашей иерархии диспетчера.

if let vc3 = self.storyboard?.instantiateViewControllerWithIdentifier("vc3") as? ViewController3 { 
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    appDelegate.window?.rootViewController!.presentViewController(vc3, animated: true, completion: nil) 
} 
+0

спасибо! ваш код работает хорошо, и этот http://stackoverflow.com/questions/26667009/get-top-most-uiviewcontroller aswell –

6

Я думаю, что есть ошибка в вашем коде, где «я» должен быть контроллер представления Предъявление представить «Vc», а не «Vc» его собственного

Ваш код

self.dismissViewControllerAnimated(true, completion: { 
       let vc = self.storyboard?.instantiateViewControllerWithIdentifier("OrderViewController") 
       vc!.presentViewController(vc!, animated: true, completion: nil) 
      }) 

Попробуйте

self.dismissViewControllerAnimated(true, completion: { 
       let vc = self.storyboard?.instantiateViewControllerWithIdentifier("OrderViewController") 
       self.presentViewController(vc!, animated: true, completion: nil) 
      }) 

надежду, что это полезно

+0

забыл отредактировать этот. код все еще не работает –

+0

Вы проверяете, является ли какой-то vc нулевым. На всякий случай, чтобы убедиться, что все в порядке, мы можем проследить проблему. – HDT

+0

Это не ноль, и теперь мой код разрешен vc = self.storyboard? .instantiateViewControllerWithIdentifier («OrderViewController») как!OrderViewController –

3
let parent = self.parentViewController! 

parent.dismissViewControllerAnimated(true, completion: { 
      let vc = self.storyboard?.instantiateViewControllerWithIdentifier("OrderViewController") 
      parent.presentViewController(vc!, animated: true, completion: nil) 
     }) 
7

вы не можете сделать это, потому что, когда UIViewController А вызывает в UIViewController B и первый контроллер уволен затем два контроллера, равны нулю.

У вас должен быть UIViewController в качестве базы, в этом случае MainViewController является базой. Вам нужно использовать протокол для вызова навигации между контроллерами.

вы можете сделать с помощью протокола скажем, например, как ниже: -

В к вашему протоколу настройки ViewController:

protocol FirstViewControllerProtocol { 
    func dismissViewController() 
} 

class FirstViewController: UIViewController { 
    var delegate:FirstViewControllerProtocol! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


    @IBAction func goBack(sender: AnyObject) { 
     self.dismissViewControllerAnimated(true) { 
      self.delegate!.dismissViewController() 
     } 
    } 

Теперь в главном контроллере представления

class MainViewController: UIViewController, FirstViewControllerProtocol { 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


@IBAction func goToFirstViewController(sender: AnyObject) { 
    let viewController = self.storyboard?.instantiateViewControllerWithIdentifier(String(FirstViewController)) as! FirstViewController 
    viewController.delegate = self 
    self.presentViewController(viewController, animated: true, completion: nil) 
} 



//MARK: Protocol 
func dismissViewController() { 
    if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier(String(SecondViewController)){ 
     self.presentViewController(viewController, animated: true, completion: nil) 
    } 
} 

Code example with storyboard:


+1

Это должен быть принятый ответ. – user2875289

0
if let vc = storyboard?.instantiateViewController(withIdentifier: "IdOfYourVC") { 

    present(vc, animated: true, completion: nil) 
} 
2

Вот решение для Swift3

Представить ViewController

let NotificationVC = self.storyboard?.instantiateViewController(withIdentifier: "NotificationVC") as! ExecutiveNotificationViewController 

self.present(NotificationVC, animated: true, completion: nil) 

Уволить ViewController:

self.dismiss(animated: true, completion: nil)