Search code examples
iosswiftuiimageview

Pass data between viewcontroller with out segues


I was able to move from one ViewController to another programmatically without any story board, now come the part where I need to transfer the data, in my rootViewController, I have data in this form:

var restaurants:[Restaurant] = [
          Restaurant(name: "Cafe Deadend",  image: "cafedeadend.jpg", isVisited: false),
          Restaurant(name: "Homei", image: "homei.jpg", isVisited: false) ]

And of course Restaurant is a class in my model section ....

Now in my rootcontroller i move to my other controller like this ......

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let detailView: DetailViewController = DetailViewController()
        
       
         detailView.restaurant = restaurants[indexPath.row]
        self.navigationController?.pushViewController(DetailViewController(), animated: false)
        
        
    }

And of course in my DetailViewController I have this

var restaurant = Restaurant()

But here when I try to show an image like this in DetailViewController, expecting the image name to come with the code in RestaurantViewController I get nil....

let imageHeader = UIImageView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
imageHeader.image = UIImage(named: self.restaurant.image)

I am always getting nil value for the image, where I should be getting the string name of image, can any one please guide where I have gone wrong and why the value is not getting transferred from one controller to other.


Solution

  • Your code has a problem in your didSelectRowAt, since you are not passing the previously created DetailViewController with a restaurant, but another newly-created DetailViewController, try this:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      let detailView: DetailViewController = DetailViewController()
      detailView.restaurant = restaurants[indexPath.row]
      self.navigationController?.pushViewController(detailView, animated: false)
    }
    

    See the change on the pushViewController method? This should do it.