Search code examples
iosswiftuitableviewuiimageview

Multi selection table view - Rotate image in custom header when section expands/collapses


Problem: When a section is expanded, the arrow in the section header rotates to point up. When I tap a cell, the arrow starts pointing down & rotates clockwise to point up (the arrow "twitches").

enter image description here

How do I get rid of the arrow's "twitch"? I want the arrow to point up when the section is expanded and point down when the section is collapsed.

CollapsibleFilterTableViewHeader

func setExpanded(expanded: Bool) {
    //Get angle of arrow (0.0 for pointing up or 180.0 for pointing down)
    let rad: Double = atan2( Double(arrowImageView.transform.b), Double(arrowImageView.transform.a))
    let deg: CGFloat = CGFloat(rad) * (CGFloat(180) / CGFloat.pi )

    if (expanded && deg == 0.0) {
        arrowImageView.rotate(.pi)
    }
}

FiltersViewController

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        header.setExpanded(expanded: filterSection.isExpanded)
        header.delegate = self
        return header
    }

func toggleSection(header: CollapsibleFilterTableViewHeader, section: Int) {
        let isExpanded = !filterSection.isExpanded

        // Toggle isExpanded
        filterSection.isExpanded = isExpanded
        header.setExpanded(expanded: isExpanded)

        filtersTableView.reloadSections(NSIndexSet(index: section) as IndexSet, with: .automatic)
    }

Sources: Stackoverflow Question, Medium Article


Solution

  • Try this out

    func setExpanded(expanded: Bool) {
    
          if (expanded) {
            arrowImageView.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
    
          } else {
           arrowImageView.transform =  CGAffineTransform.identity
    
          } 
        }
    

    Set rotation when expanded otherwise provide CGAffineTransform.identity to reset

    Hope it is helpful to you