Search code examples
iosswiftuitableviewuisegmentedcontrol

UISegmentControl with UITableView - UITableViewCell layout remains same on changing the segment


In the scenario mentioned in the question title, on changing the segment, ideally the UITableView should reload and hence the UITableViewCell should also reload. The issue is, all the content gets updated like label texts. But if I have expanded a subview of cell in one segment, it remains still expanded after segment is changed.
Segment index change function :

@IBAction func segmentOnChange(sender: UISegmentControl)
{
    // Few lines
    // self.tableMenu.reloadData()
}

Screenshot 1 :

enter image description here

Screenshot 2 :

enter image description here

So ideally, in screenshot 2, the cart view should have been collapsed.

Update :

Show/Hide view :

func showHideCartView(sender: UIButton)
    {
        let cell = self.tableMenu.cellForRow(at: IndexPath(row: 0, section: Int(sender.accessibilityHint!)!)) as! RestaurantMenuItemCell
        if sender.tag == 1
        {
            // Show cart view
            cell.buttonArrow.tag = 2
            cell.viewAddToCart.isHidden = false
            cell.constraint_Height_viewAddToCart.constant = 50
            cell.buttonArrow.setImage(UIImage(named: "arrowUp.png"), for: .normal)
        }
        else
        {
            // Show cart view
            cell.buttonArrow.tag = 1
            cell.viewAddToCart.isHidden = true
            cell.constraint_Height_viewAddToCart.constant = 0
            cell.buttonArrow.setImage(UIImage(named: "arrowDown.png"), for: .normal)
        }

        self.tableMenu.reloadData()
    }  

cellForRowAtIndexPath :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "RestaurantMenuItemCell", for: indexPath) as! RestaurantMenuItemCell
        cell.selectionStyle = .none
        let menuItem = self.menuItems[indexPath.section]
        cell.imageViewMenuItem.image = UIImage(named: "recommend0@2x.png")
        cell.labelName.text = menuItem.name
        cell.labelDescription.text = menuItem.description
        cell.labelPrice.text = String(format: "$%i", menuItem.price!)
        cell.buttonArrow.accessibilityHint = String(format: "%i", indexPath.section)
        cell.buttonArrow.addTarget(self, action: #selector(self.showHideCartView(sender:)), for: .touchUpInside)

        return cell
    }

Solution

  • Since you rely on the sender button's tag to determine whether the cell should be shown in expanded or collapsed state, you need to make sure that when the segment changes, the tags for all the cells' buttonArrow also change to 1.

    Unless that happens, the cells will be reused and since the buttonArrow's tag is set to 2, it will be shown as expanded.