2015-02-10 7 views
2

Я довольно новичок в разработке Swift, и я попытался обратиться к API Swift UIAlertController, но не смог понять, как перейти к другому UIViewController после нажатия кнопки на UIAlertController.Перейти к ViewController от кнопки UIAlertController нажмите

Я бы по достоинству оценил любые указатели, помощь или решение этой проблемы. Мой фрагмент кода приведен ниже -

@IBAction func showAlert() { 

    let alertController = UIAlertController(title: "Disclaimer", message: "Disclaimer Text Here", preferredStyle: .Alert) 


    let declineAction = UIAlertAction(title: "Decline", style: .Cancel, handler: nil) 
    alertController.addAction(declineAction) 

    let acceptAction = UIAlertAction(title: "Accept", style: .Default) { (_) -> Void in 

     let secondVC = ViewController(nibName: "ViewController", bundle: nil) 
     let navController = UINavigationController(rootViewController: secondVC) 
     self.presentViewController(navController, animated: true, completion: nil) 

    } 
    alertController.addAction(acceptAction) 

    presentViewController(alertController, animated: true, completion: nil) 

} 

То, что я пытаюсь сделать здесь, когда кнопка нажата отказ от ответственности отображается AlertController. Если выбрано кнопка «Отклонить», отменяется действие, и если выбрано «« Принять », приложение должно перейти к контроллеру навигации, который затем позволяет перейти к другим ViewControllers, используя меню в приложении.

Раньше я использовал панель рассказов, чтобы связать кнопку с NavigationController, чтобы перейти к ViewController, который я хотел. Теперь я хочу сделать то же самое программно для AlertController «Принять» Кнопка.

Заранее спасибо.

ответ

2

В основном, чтобы связать кнопку UIAlertViewController с UIViewController UINavigationController, нам нужно будет создать ручной сеанс между UIViewController, который имеет U IAlertViewController в UINavigationController.

Пожалуйста, обратитесь к этому снимок экрана, чтобы увидеть, как сделать выше -

enter image description here

Затем выберите связь между UIViewController и UINavigationController. Перейдите на левую боковую панель и выберите инспектор атрибутов и назовите идентификатор.

Теперь написать в коде -

@IBAction func showAlert() { 

let alertController = UIAlertController(title: "Disclaimer", message: "Before using this teaching resource, you confirm that you agree:\n1. To obey the law regarding data protection and patient confidentiality.\n2. To us this app professionally and appropriately in clinical settings.\n3. This is for your personal use and you may not modify, distribute, publish, transfer any information obtained from this teaching resource without the developers' permission.\n4. In no event shall the developer be liable to you for any loss arising from your use of this resource.", preferredStyle: .Alert) 

let declineAction = UIAlertAction(title: "Decline", style: .Cancel, handler: nil) 
let acceptAction = UIAlertAction(title: "Accept", style: .Default) { (_) -> Void in  

    self.performSegueWithIdentifier("SomeSegue", sender: self) // Replace SomeSegue with your segue identifier (name) 
} 

alertController.addAction(declineAction) 
alertController.addAction(acceptAction) 

presentViewController(alertController, animated: true, completion: nil) 
} 
1

Это использование блока обработчика. Вы должны сделать желаемое действие в этом блоке.

Edit: Код

let acceptAction = UIAlertAction(title: "Accept", style: .Default, handler:{ action in 
    //Write your code here 
}) 

Вы можете использовать эту ссылку в качестве ссылки: http://www.appcoda.com/uialertcontroller-swift-closures-enum/

+0

Не могли бы вы опубликовать пример фрагмент кода только в качестве примера? Большое спасибо –

+1

Я отредактировал свой ответ. –

+0

Благодарим вас за ссылку. Теперь я могу это сделать, мне было интересно, могу ли я перейти к диспетчеру просмотра NavigationController, чтобы он позволял мне перемещаться дальше в приложении с помощью меню. –

2

Вам необходимо реализовать блок обработчика для выполнения кода при выборе действия:

@IBActionfunc showAlert() { 

    let alertController = UIAlertController(title: "Disclaimer", message: "Disclaimer Text Here", preferredStyle: .Alert) 


    let declineAction = UIAlertAction(title: "Decline", style: .Cancel, handler: nil) 
    alertController.addAction(declineAction) 

    let acceptAction = UIAlertAction(title: "Accept", style: .Default) { (_) -> Void in 

     let secondVC = SecondViewController(nibName: "SecondView", bundle: nil) 
     let navController = UINavigationController(rootViewController: secondVC) 
     self.presentViewController(navController, animated: true, completion: nil) 
    } 
    alertController.addAction(acceptAction) 

    presentViewController(alertController, animated: true, completion: nil) 

} 
+0

Thats awesome от вас! Благодаря! :) Теперь, как перейти к NavigationController, используя ту же кнопку, а не только один диспетчер представлений? Другие контроллеры просмотра связаны с NavigationController. –

+0

Я отредактировал свой ответ, если правильно понял вас;) –

+0

Я думаю, вы поняли, что я имею в виду! Я отредактировал мой код из вашей справки, он прекратил выполнение и говорит «Thread 1: signal SIGABRT». Любая идея, где я могу поступить неправильно? –

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