Reputation: 694
I display a shopping list for different product groups as a table view with multiple sections. I want to add items with an add button for each group. So I equipped the header cell with a UIToolbar
and a + symbol as a UIBarButtonItem
.
Now every product group has an add button of his own:
If one add button was pressed, I have a problem identifying which one was pressed.
prepareForSeque(...)
delivers a sender of type UIBarButtomItem
, but there is no connection to the header cell from were the event was triggered.IBAction
to the UITableViewController
, the received sender is also of type UIBarButtomItem
, and there is no connection to the header cell, too.IBAction
to my CustomHeaderCell:UITableViewCell
class, I am able to identify the right header cell.This line of code returns the header cell title:
if let produktTyp = (sender.target! as! CustomHeaderCell).headerLabel.text
However, now the CustomHeaderCell
class has the information I need.
But this information should be available in the UITableViewController
.
I couldn't find a way to feed the information back to the UITableViewController
.
import UIKit
class CustomHeaderCell: UITableViewCell {
@IBOutlet var headerLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
@IBAction func neuesProdukt(sender: UIBarButtonItem) {
if let produktTyp = (sender.target! as! CustomHeaderCell).headerLabel.text
{
print(produktTyp)
}
}
}
Upvotes: 0
Views: 245
Reputation: 596
Here's how I typically handle this:
Use a Closure to capture the action of the item being pressed
class CustomHeaderCell: UITableViewCell {
@IBOutlet var headerLabel: UILabel!
var delegate: (() -> Void)?
@IBAction func buttonPressed(sender: AnyObject) {
delegate?()
}
}
When the Cell is created, create a closure that captures either the Index Path or the appropriate Section.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let section = indexPath.section
let cell = createCell(indexPath)
cell.delegate = { [weak self] section in
self?.presentAlertView(forSection: section)
}
}
Upvotes: 1