Why the property does not pass to another view Controller?

53 Views Asked by At
extension ReservationViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if let vc = storyboard?.instantiateViewController(withIdentifier: "restaurantDetail") as?  RestaurantViewController {
            vc.restaurantNametxt = searchRestaurant[indexPath.row].restaurantName
            print(searchRestaurant[indexPath.row].restaurantName)
        }
        print(indexPath.row)
        print(searchRestaurant[indexPath.row].restaurantID ?? "")
        restaurantsTableView.deselectRow(at: indexPath, animated: true)
        performSegue(withIdentifier: "restaurantDetail", sender: self)
    }
}

class RestaurantViewController: UIViewController {
    
    @IBOutlet weak var restaurantName: UILabel!
    @IBOutlet weak var reserverButton: UIButton!
    
    var restaurantNametxt: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        restaurantName.text = restaurantNametxt
        print(restaurantNametxt)
    }
    
    
    @IBAction func reserverButtonPressed(_ sender: UIButton) {
        performSegue(withIdentifier: "FinalStep", sender: self)
        self.navigationItem.hidesBackButton = true
    }
}

When the user performs didSelectRow at I want to pass searchRestaurant[indexPath.row].restaurantName to another vc which is RestaurantViewController but on UILabel is still "".

vc.restaurantNametxt contains the real restaurantName because it is printing the value.

1

There are 1 best solutions below

2
burnsi On

Your approach fails because you do not use the vc you instantiated. With performSegue you create a new ViewController that gets presented. And its property is empty as you already discovered.

Try:

self.presentViewController(vc, animated: true, completion: nil)

and remove:

performSegue(withIdentifier: "restaurantDetail", sender: self)