belgrim
belgrim

Reputation: 123

How do I avoid using a million view controllers for tableview list?

Here's an example of what I want to do.

You have a table view with a list of different videos. When you click on a video it takes you to a detailed view controller (video at the top, description below). Right now I currently create a brand new view controller, add the video/text, link the segue, and then create another view controller and start over. Instead of having a million view controllers, can't you do this with just one view controller and feed in the text/video from a swift file? I am relatively new so if someone could explain the process crystal clear it would be much appreciated. Thanks!

Upvotes: 2

Views: 76

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100549

Yes , you can do it with 2 vcs ( the list & detail ) only , by doing this ( known as Dependency Injection)

let vc = YourTableVC()
vc.arr = // set arr here
present///

class YourTableVC : UITableViewController {
  var arr = [YourModel]()
}

Where the model

struct YourModel {
  // add properties
}

same idea applies to navigation from list to detail

Upvotes: 2

Sweeper
Sweeper

Reputation: 275125

You only need one VC to display the many videos you have.

Let's say you have a model like this:

struct Video {
    let videoLink: URL
    let description: String
}

And your table view controller uses an array of Videos called videos as its data source.

In your didSelectRowAt method, you can get the selected video and perform a segue with the selected video as the sender:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let videoSelected = videos[indexPath.row]
    performSegue(withIdentifier: "showVideo", sender: videoSelected)
}

Now create a single VideoViewController.swift file and do something like this:

class VideoViewController: UIViewController {
    var video: Video!

    // write code for this VC to display not a specific video, but "self.video"
    // For example, instead of setting the label's text to a hardcoded description, set it to "self.video.description"
}

Then, go back to your table view controller, and override prepareForSegue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? VideoViewController {
        vc.video = sender as! Video
    }
}

Upvotes: 3

Related Questions