DevX
DevX

Reputation: 541

Object is not setup correctly when passing it across classes

I'm having trouble pushing new ViewController in swift.

class CartViewController: UITableViewController  {

    static var items:[Item] = []

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return CartViewController.items.count
    }

    //if cell is selected
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = storyboard?.instantiateViewController(withIdentifier: "PaymentController") as! PaymentController
        print(CartViewController.items[indexPath.row].title)
        vc.item? = CartViewController.items[indexPath.row]

        self.navigationController?.pushViewController(vc, animated: true)
    }

The print function up there gives the right result, but there's nothing showing up when the new vc is pushed. debugger shows the vc.item is nil.

This is what I have in PaymentController class

class PaymentController: UIViewController {

    @IBOutlet weak var myImage: UIImageView?
    @IBOutlet weak var myTitle: UILabel?
    @IBOutlet weak var myPrice: UILabel?

    var item:Item?

    override func viewDidLoad() {
        super.viewDidLoad()

        myImage?.image = UIImage(named: item!.image)
        myTitle?.text = item!.title
        myPrice?.text = String(item!.price)
    }
}

Any hints or ideas will be appreciated:))

Upvotes: 0

Views: 44

Answers (1)

Yonat
Yonat

Reputation: 4608

In tableView(_,didSelectRowAt:) try removing the ? in line 3.
I.e., replace vc.item? = (...) with vc.item = (...)

Upvotes: 1

Related Questions