gpt4 book ai didi

swift - 在 Swift 中的 2 个 View Controller 之间传递数据

转载 作者:可可西里 更新时间:2023-11-01 00:37:26 24 4
gpt4 key购买 nike

我有 2 个 View Controller ,分别创建。它不是导航 Controller 或其他。我为它们分别创建了 2 个文件:ViewController.swiftSecondViewController.swift。第二个 VC 称为 audioList

在第一个 VC 中,我有一个按钮,单击它我将使用代码打开第二个 VC

dispatch_sync(dispatch_get_main_queue(), { () -> Void in

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController
self.presentViewController(controller, animated: true, completion: nil)

})

在SecondViewController中有一个名为music的数组。我想在代码之前用元素填充它,您可以在上面看到 - 来自 1-st VC。

我读过 thisthat一篇文章和其他文章阅读了有关通过创建具有更改数据功能的协议(protocol)来做到这一点的文章,尝试了很多 segues,它们的执行和 prepareFor 功能 - 但没有任何效果。

请帮助我从 button-click-action in 1-st VC 填充 array in 2-nd VC

更新:

SecondViewController.swift 中我有这段代码:

var music: [String] = ["test"]

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return music.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "mycell")
cell.textLabel!.text = music[indexPath.row]

return cell
}

最佳答案

在您的第一个 View Controller 上创建并填充一个数组。然后在第二个 View Controller 上声明一个相同结构的数组。然后将其填入segue。

VC1:

    var music : [String] = ["Song1", "song2", "Song3"]

dispatch_sync(dispatch_get_main_queue(), { () -> Void in

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController

controller.music2 = self.music

self.presentViewController(controller, animated: true, completion: nil)
})

VC2:

    import UIKit

class audioList: UIViewController {
var music2 : [String]

viewDidLoad()
{

}
}

关于swift - 在 Swift 中的 2 个 View Controller 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32012465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com