简体   繁体   中英

Adding items to tableview with sections

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.

  1. If I connect the add button with a seque, the function prepareForSeque(...) delivers a sender of type UIBarButtomItem , but there is no connection to the header cell from were the event was triggered.
  2. If I connect an IBAction to the UITableViewController , the received sender is also of type UIBarButtomItem , and there is no connection to the header cell, too.
  3. If I connect an 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)
        }
    }
}

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)
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM