发送一个整数回到先前的视图控制器

问题描述:

你好,我正在尝试返回一个变量,具有级别号码。在用户清除下方那个圆圆的被称为发送一个整数回到先前的视图控制器

 if enemyHP <= 0.0{ 
      level = level + 1     
      battle(winPlayer:true) 
     } 

则函数的战斗被称为

 let alert = UIAlertController(title: "finished!", message: finishedMessage, preferredStyle: UIAlertControllerStyle.alert) 
     alert.addAction(UIAlertAction(title:"Go Back",style:.default,handler:{action in 


     self.dismiss(animated: true, completion: nil)})) 
     self.present(alert,animated: true,completion: nil) 
    } 

我想显示在一个视图控制器的级别数,所以我需要变量层面去是传了回去。这是最好的方法是什么?我使用了segues,它不适用于警报。

代表

protocol DataSentDelegate { 

    func Back(data: Int) 
} 

我用

delegate?.Back(data: level) 

在前面视图控制器我加

func Back(data: Int){ 
    new = data 
} 


print(new) 

它不会出现。

+0

您的代码将无法使用。你正在解雇,那么你提出? – Brandon

+0

@Brandon你好,它工作。它显示了警报,它将我带回。我无法将变量传回 – Satsuki

+2

请参阅https://*.com/questions/5210535/passing-data-between-view-controllers – rmaddy

除了使用解雇至今方法,你应该使用赛格瑞然后传递对象准备(为:发件人:)这样:

func prepare(for segue:UIStoryboardSegue, sender:Any?) 
{ 
    if segue.identifier == "Back" // Give it any name 
    { 
     if let destination = segue.destination as? MyViewController // NOTE: this is your custom view controller class 
     { 
      destination.level = yourDesiredValue 
     } 
    } 
} 

更新:到执行segue:

let alert = UIAlertController(title: "finished!", message: finishedMessage, preferredStyle: UIAlertControllerStyle.alert) 
alert.addAction(UIAlertAction(title:"Go Back",style:.default,handler:{action in 
    self.performSegue(withIdentifier: "Back", sender: nil) 
} 
self.present(alert,animated: true,completion: nil) 
+0

你好谢谢你的回答,我知道关于segues,但这将工作与警报? – Satsuki

+0

@Satsuki我不知道你在做什么,我不明白你为什么试图在同一个警报的完成回调中提出警报。我想你想在完成块外面显示警报,并且当用户按下警报的“返回”操作时,你想执行该警报。我编辑了答案,我希望它有帮助。 –

+0

谢谢!这做到了。我需要更多地了解segues .. – Satsuki