快速通过segue传递数组 [英] Passing array through segue in swift

查看:60
本文介绍了快速通过segue传递数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Swift将数组从SecondViewController传递到FirstViewController到现在,我已经苦苦挣扎了几天.

I've been struggling for a few days now with passing an array from my SecondViewController to my FirstViewController using Swift.

从我的研究中,我发现将segueprepareForSegue一起使用是可行的选择,但我似乎无法弄清楚.我在做什么错了?

From my research I found that segue with prepareForSegue would be a viable option but I can't seem to figure it out. What am I doing wrong?

我在SecondViewController中的prepareForSegue看起来像这样:

My prepareForSegue in SecondViewController looks like this:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        var DVC: FirstViewController = segue.destinationViewController as! FirstViewController
        DVC.mySeguedArray = myIncomeArray
}

我的FirstViewController看起来像这样:

My FirstViewController looks like this:

class FirstViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
var myIncomeArray: [Income] = []
var mySeguedArray: [Income] = []

override func viewDidLoad() {
    super.viewDidLoad()
    myIncomeArray = mySeguedArray
}

还值得一提的是,我确定要在SecondViewController中填充数组,因为在测试时,通过向其添加新的Income对象时打印出数组的大小来测试它.但是FirstViewController中的数组在segue之后检查其大小时只会返回0.

Also worth mentioning is that I'm sure I'm populating the array in the SecondViewController as I'm testing it by printing out the size of the array when adding new Income objects to it. But the array in FirstViewController just returns 0 when checking it size after segue.

添加了情节提要的图片 故事板

Added picture of storyboard StoryBoard

推荐答案

您的代码看起来不错,请使用以下prepareforsegue,因为它有助于找出问题出在哪里

Your code looks fine, use the following prepareforsegue as it helps figure out where the problem could be

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "segueIdInStoryboard" {
        if let DVC = segue.destinationViewController as? FirstViewController{
            DVC.mySeguedArray = myIncomeArray
        } else {
            print("Data NOT Passed! destination vc is not set to firstVC")
        }
    } else { print("Id doesnt match with Storyboard segue Id") }
}

class FirstViewController: UIViewController 
{
     @IBOutlet weak var textView: UITextView!
     var myIncomeArray: [Income]!
     var mySeguedArray: [Income]!{
         didSet{
             myIncomeArray = mySeguedArray //no need to call viewDidLoad
         }
     }
}

这篇关于快速通过segue传递数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆