Search code examples
iosswiftuitableviewibactionuitableviewsectionheader

Action affecting buttons in all TableView Headers


I am using a custom UITableViewHeaderFooterView for me TableView. I was trying to implement hiding and showing rows in a section(which I have working). I decided to add a button (>) to the section header so that I can rotate it when the section is "expanded/collapsed".

The problem I have appears when I click the button. When the rotateCollapseButton() function is called, the (>) buttons in all the section headers rotate, not just the one that was clicked. Sometimes it'll even exclude the button that was clicked or clicking one will affect a different one and not itself. How can I make it so that only the correct button will rotate?

This is the code I have for the custom Header I created.

var rotated:Bool = false

var section:Int?

weak var delegate:MessageGroupHeaderDelegate?

@IBAction func expandCollapseButtonClicked(_ sender: Any) {
    rotateCollapseButton(sender as! UIButton)
    delegate?.didPressExpandCollapseButton(atSection : self.section!)
}

func rotateCollapseButton(_ button:UIButton) {
    UIView.animate(withDuration: 0.5) { () -> Void in
        var rotationAngle:CGFloat = CGFloat(M_PI_2)

        if self.rotated {
            rotationAngle = CGFloat(0)
        }

        button.transform = CGAffineTransform(rotationAngle : rotationAngle)

        self.rotated = !self.rotated
    }
}

EDIT: Code where the header is initialized...

 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    // Dequeue with the reuse identifier
    let cell = self.massMessageGroupsTableView.dequeueReusableHeaderFooterView(withIdentifier: "MessageGroupTableViewHeader")
    let header = cell as! MessageGroupTableViewHeader
    header.groupNameLabel.text = messageGroupsMap[section]?.messageGroup.name
    header.section = section
    header.setComposeButtonImage()
    header.delegate = self

    return cell
}

Thank you!


Solution

  • In your header setting, trying doing this instead:

     func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        // Dequeue with the reuse identifier
        let cell = self.massMessageGroupsTableView.dequeueReusableCell(withIdentifier: "MessageGroupTableViewHeader")
        let header = cell as! MessageGroupTableViewHeader
        header.groupNameLabel.text = messageGroupsMap[section]?.messageGroup.name
        header.section = section
        header.setComposeButtonImage()
        header.delegate = self
    
        let containingView : UIView = UIView()
        containingView.addSubview(header)
    
        return containingView
    }