Passing data between 2 view controllers in Swift

巧了我就是萌 提交于 2019-12-11 03:29:37

问题


I have 2 view controllers, created separately. It's not navigation controller or other. I've 2 files for each of them: ViewController.swift, SecondViewController.swift. Second VC is called audioList

In 1-st VC I have a button and by clicking on it I'm opening second VC using code

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)

})

There is an array called music in SecondViewController. I want to fill it with elements before code which you can see upper - from 1-st VC.

I've read this and that one post, others, read about doing it by creating protocol with function which changes data, tried a lot with segues, their performing and prepareFor-functions - but nothing worked.

Help me please with filling array in 2-nd VC from button-click-action in 1-st VC

Update:

In SecondViewController.swift I have this code:

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
}

回答1:


Create and fill an array on your first view controller. Then declare an array of the same structure on your second view controller. Then fill it in the 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()
        {

        }
}



回答2:


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


来源:https://stackoverflow.com/questions/32012465/passing-data-between-2-view-controllers-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!