reloading uitableview from a button in a swift class

You can reload the table view every time your cartArray updates.

Simply do the following

var cartArray =  [Cart(name: "initial", thumbnails: "sgA1.jpg", price: "initial", quantity: 0)] {
    didSet { 
       NotificationCenter
           .default
           .post(Notification(name: "cartArrayUpdated"))
    }
}

Then add your CartViewController as observer for that notification

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.dataSource = self
    tableView.reloadData()
    NotificationCenter
       .default
       .addObserver(self, 
                    selector: #selector(refresh), 
                    name: .init("cartArrayUpdated"), 
                    object: nil)
    // Do any additional setup after loading the view.
}

Then inside CartViewController just create the function that handles your tableview refresh

@objc func refresh() {
    tableView.reloadData()
}

Also don’t forget to remove CartViewController as observer when is no longer needed. After viewDidLoad add the following

deinit {
    NotificationCenter.default.removeObserver(self)
}

Also I agree with @Leo Dabus declaring this array as global variable is a bad practice. You should have this inside CartViewController then all you had to do is just

var cartArray =  [Cart(name: "initial", thumbnails: "sgA1.jpg", price: "initial", quantity: 0)] {
    didSet { 
       tableView.reloadData()
    }
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top