2016-02-19 3 views
2

Вот мой кодUIAlertView не возвращает соответствующее значение

import Foundation 
import UIKit 

class Alert: UIViewController { 


class func showAlert(title: String, message: String, buttonTitle: String? = nil, buttonTitle2: String? = nil, sender: UIViewController) -> Int? { 
    var flag : Int? 
    func yes(){ 
     flag = 1 

    } 
    func no(){ 
     flag = 0 

    } 
    //= nil ; 
    if objc_getClass("UIAlertController") != nil { 
     let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) 
     if (buttonTitle != nil){ 
      alert.addAction(UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in 
      yes() 


     })) 
     } 
     if (buttonTitle2 != nil) { 
      alert.addAction(UIAlertAction(title: buttonTitle2, style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction!) in 
       no() 

      })) 
     } 


     sender.presentViewController(alert, animated: true, completion: nil) 

     return flag 


    } else { 
     let alert = UIAlertView() 
     alert.title = title 
     alert.message = message 
     alert.addButtonWithTitle(buttonTitle) 
     alert.addButtonWithTitle(buttonTitle2) 
     print("inside Else") 

     alert.show() 
     return flag 
     //make and use a UIAlertView 
    } 

} 


} 

Проблема заключается в том, что флаг получение возвращается всегда ноль в контроллер просмотра я зову Сигнал с. Мне нужно, чтобы флаг возвращался 1, если «да» нажата, и 0, если нажата «Нет». Я застрял в этой проблеме много времени. Помогите.

+0

Это 'UIAlertController'. 'UIAlertView' устарел. –

ответ

0

Вы сделали ошибку, что закрытие не будет выполняться, пока кнопка не нажата, но функция будет возвращать правильный now.you должен доставить к закрытию этой function.It будет выглядеть следующим образом:

class func showAlert(title: String, message: String, buttonTitle: String? = nil, buttonTitle2: String? = nil, sender: UIViewController,handler: ((Bool) -> Void)) -> Void 

И справиться с этим в боевой готовности действие, как это:

handler(true) 
+0

Как добавить значение по умолчанию для обработчика, вызванное вызовом showAlert во многих случаях, и все не нуждаются в возвращаемом значении? – MrDank

+0

Даже если я не передаю параметр обработчика, показать предупреждение должно быть выполнено. – MrDank

+0

@DarthVader Вы должны обработать действие click в закрытии, если вы не можете этого сделать, используйте закрытие, чтобы передать это действие. Помните об этом. – Lumialxk

2

Попробуйте этот код,

import UIKit 

class ViewController: UIViewController { 

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 showAlert() { 
    let alertController = UIAlertController(title: "Hey there", message: "Do you want to do it?", preferredStyle: .Alert) 

    let btnAction1 = UIAlertAction(title: "Yes", style: .Default) { (action : UIAlertAction) -> Void in 
     self.yes() 
    } 

    let btnAction2 = UIAlertAction(title: "No", style: .Default) { (action : UIAlertAction) -> Void in 
     self.no() 
    } 

    alertController.addAction(btnAction1) 
    alertController.addAction(btnAction2) 

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

func yes() -> Int 
{ 
    print("Yes") 
    return 1 
} 

func no() -> Int 
{ 
    print("No") 
    return 0 
} 
} 

Сво работает отлично ее e, я надеюсь, что это сработает и для u .. :)

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