Get section number in custom cell button action

后端 未结 5 1207
北恋
北恋 2021-01-13 23:42

I have a tableView dynamically populated with custom cells in several sections.

In my CustomCell class I have an @IBAction for a custom checkbox button in the cell.

5条回答
  •  生来不讨喜
    2021-01-13 23:44

    I have recently come with a solution to this problem leveraging the use of Segues and implementing it in Swift 2.2 and XCode8.

    I have a Custom Cell that I'm using for a header that has 2 Labels and a UIButton. All of my data is in an array and I want to dynamically access the data. Each section is an array of section headers and within that class the sections contain additional arrays to finish generating my tableView. My goal was to get the Index of the section based on a button click in the custom cell (header) and change the data in a different view.

    To populate the tableView with my custom header cells I used:

    override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let myCell = tableView.dequeueReusableCellWithIdentifier("REUSABLE ID")! as! MyHeaderCell
        let team = array[section]
        myCell.teamName.text = team.name
        myCell.projectName.text = team.project
        myCell.addMemberButton.tag = section        
        return myCell
    }
    

    Using the storyboard, the IBOutlet for the button (addMemberButton) in MyHeaderCell had the .tag field which I used to save the section index. So when I prepared segue I could use this value to dynamically access my array in the DataSource. As follows

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "segue1" {
    
            ...
    
        }else if segue.identifier == "AddMemberSegue"{
            let ix = sender?.tag
            let destVC = segue.destinationViewController as! AddMemberViewController
            self.myArray = array[ix!]
            destVC.delegate = self
    
        }else if segue.identifier == "segue3"{
    
           ...
    
        }
    } 
    

    Here the sender is the button, so the .tag field gives us the specific section index to access the correct location in the array

    Hope this helps someone.

提交回复
热议问题