Reputation: 103
I have a UITableViewController
with custom UITableViewCell
, and every cell has an UISwitch
inside.
Need to update an information on my table (a string in the header), when any of these switches turn on/off (need to display the number of switches on in the section header).
I'm not confident with iOS and UIKit, but I've already found 2 possibile solutions:
tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
In the first solution my TableViewController
conforms to
protocol TableViewDelegate {
func reloadTable()
}
that update its inner counter of switches on - and update the header section in function tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
- calling
DispatchQueue.main.async{
self.tableView.reloadData()
}
Obviously my custom UITableViewCell
has the reference to the delegate TableViewController
and call its reloadTable()
.
The second solution instead is about the possibility to get the information of every cell in the method cellForRowAt indexPath
. I've found that this function in not only called when the table has to be drawn, but also when I interact with a component into a cell.
So I need to implement a counting in the function cellForRowAt indexPath
? Or the first solution with delegate pattern is a good one?
Upvotes: 0
Views: 88
Reputation: 2675
you should use a delegate in your cell.. can go like this
protocol CellDelegate: class {
func actionDidPressed()
}
then in your cell should use it
class cell: UITableViewCell {
weak var delegate: CellDelegate?
@IBAction func buttonPressed() {
delegate?.actionDidPressed()
}
}
then lastly in your controller you can conform to it
class ViewController: UIViewController {
// in your cellAtIndexPath method after creating cell you can
cell.delegate = self
}
I prefer to make an extension to the View Controller to conform to delegates
extension ViewController: CellDelegate {
func actionDidPressed() {
// add the action you need here
}
}
Upvotes: 1
Reputation:
You can use NSNotification to pass data between different views. You'll need to register the recipient controller by using the addObserver
method and use post to send a message. You can refer to this post
Upvotes: 0