2016-10-28 65 views
0

我正在使用Swift即Rock,Paper和Scissors制作iOS应用程序。如何使用Swift 3.0按钮将ViewController的值传递给另一个ViewController

当您按下哪个按钮(带有摇滚图片,图片图片或剪刀图片)时,它会延续到不同的视图控制器,并显示它是平局,胜利还是损失(比较您的数字[即。摇滚按钮是1]由电脑随机数)。但它不会显示结果,因为它需要在按钮中,而不是在按钮和viewDidLoad()之外。

我会给你我的代码片段。我正在使用下一个视图控制器中的函数来返回一个字符串。

所以我需要帮助的是通过将userNum和computerNum传递给按钮中的下一个视图控制器(当按下时)然后调用该函数并返回字符串。

var userNum: Int = 0 
var computerNum: Int = 0 

@IBAction func rock(_ sender: UIButton) { 
    userNum = 1 
    computerNum = (Int)(arc4random_uniform(3) + 1) 
} //This next code will be in the other View Controller 
func chooseWinner(userNum : Int, computerNum : Int) -> String { 
    if userNum == computerNum { 
     return "There is a tie" 
    }else if userNum == 1 && computerNum == 2{ 
     return "You lost!" 
    }else if userNum == 1 && computerNum == 3{ 
     return "You won!" 
    }else if userNum == 2 && computerNum == 1{ 
     return "You won!" 
    } 
    else if userNum == 2 && computerNum == 3{ 
     return "You lost!" 
    }else if userNum == 3 && computerNum == 1{ 
     return "You lost!" 
    } 
    else if userNum == 3 && computerNum == 2{ 
     return "You won!" 
    }else{ 
     return "value" 
    } 
} 
+0

尝试使用标识符执行segue ... – Joe

+0

我尝试过,但我不知道如何传递值。 – FusionPointInc

回答

3

在故事板编辑器中,按住Ctrl同时按住leftclick和鼠标拖动到要Segue公司到目的地视图控制器。一旦释放鼠标,您就可以选择一种类型。 show

这将允许您继续使用您的目标视图控制器,而不必像编程中那样以编程方式创建IBAction

在源视图控制器,添加功能

prepare(for segue: UIStoryboardSegue, sender: Any?)

,这将让你检查是否有赛格瑞和segueing之前做任何额外的设置。

记得设置的标识符在属性您SEGUE Inpector

identifier

内源的ViewController

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if segue.identifier == "destination" { 


     //OtherViewController is a placeholder for the viewcontroller class of your destination viewcontroller 
     if let destinationVC = segue.destinationViewController as? OtherViewController { 
      destinationVC.userNum = 1 
      destinationVC.computerNum = (Int)(arc4random_uniform(3) + 1) 
     } 
    } 
} 

内部目的地视图控制器

var userNum: Int! 
var computerNum: Int! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    //do wtv you need with your values 
    print(chooseWinner(userNum: userNum, computerNum: computerNum)) 
} 
+0

是吗?而不是AnyObject?好的?它不会让我做AnyObject而不删除覆盖。 – FusionPointInc

+0

很好的观察!我没有意识到他们从AnyObject更改为Any。 – Danoram

+0

id是否导入为Any?而不是Swift 3中的AnyObject。 –

相关问题