快速将数据传递到数组

时间:2018-11-11 22:47:30

标签: ios arrays swift segue

我希望将数据通过文本框传递到数组(第二视图控制器)中,因此可以将其添加到数据池中并随机选择。

例如,您将在第一个VC中的文本字段中输入您的姓名(和/或其他名称),然后进入一个数组,该数组将告诉他们第二个VC中显示的颜色。

本质上,我试图将数据传递给变量(它将保存所有输入的名称),并将变量附加到数组,然后单击按钮生成并通过arc4random随机从数组中拉出。我的问题是它没有追加。任何帮助将不胜感激。

这是我的代码:

VC 1:

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 StartTapped(_ sender: Any) {
        performSegue(withIdentifier: "SecondViewControllerSegue", sender: self)


    }
    @IBOutlet weak var AddPlayerTextField: UITextField!



    @IBAction func AddTexttoArrayBtn(_ sender: Any) {
        if AddPlayerTextField.text == nil
        {
            performSegue(withIdentifier: "SecondViewControllerSegue", sender: self)
    }
        func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            let SecondViewController = segue.destination as! ViewController2
            SecondViewController.myString = AddPlayerTextField.text!

VC 2:

导入UIKit

class ViewController2: UIViewController {

    var myString = String ()

    var TeamBuildingQuestions = [ "is Red", "is Blue", "is Green", "is Purple","is Teal","is Orange", "is Red", "is Grey", "is Pink"]

    var MasterTeamBuildingQuestionsArray = [ "Hello", "beep bop bbeep", "Boop", "Bap","Bospop","bob the builder"]


    @IBOutlet weak var DisplayArray: UILabel!


    @IBAction func NextQuestionBtn(_ sender: Any) {

        let RandomArrayNumber = Int (arc4random_uniform(UInt32(TeamBuildingQuestions.count)))
        let QuestionDisplayed = TeamBuildingQuestions[RandomArrayNumber]
        DisplayArray?.text = QuestionDisplayed
    }


    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.



        TeamBuildingQuestions.append(myString)


    }

2 个答案:

答案 0 :(得分:0)

在VC2中,代替didReceiveMemoryWarning,在viewDidLoad中实现TeamBuildingQuestions.append(myString)。

答案 1 :(得分:0)

这是一个错误:

 if AddPlayerTextField.text == nil{
}

应该是

  if AddPlayerTextField.text != nil && AddPlayerTextField.text.count > 0{
}