ytpm
ytpm

Reputation: 5150

Different UITableViewCell subviews layout after tapping a cell

I've created a UITableView which has number of cells. All the cells are the same, I want to change the cell's subviews layout and the cell's height after tapping the cell. It's pretty easy to change the height of the cell itself, but I can't figure out how to change the cell's subviews layout...

Should I reload a new custom cell instead the tapped cell or just update the cell subviews frame?

This is the normal layout:

el

This is the new layout:

el

The constraints are not an issue, my question is how to add elements which were unused in a normal cell and now they needed to be reframed and enlarge (such as the main UIImageView and UILabel's)

Upvotes: 0

Views: 343

Answers (1)

Rob C
Rob C

Reputation: 5073

I'd have different cells and reload them as the cells are clicked.

class TableViewController: UITableViewController {

    var largeRow: IndexPath?

    var data: [Int] = [0, 1, 2, 3, 4, 5, 6, 7]

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

extension TableViewController {

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath == largeRow {
            return makeLargeCell(at: indexPath)
        } else {
            return makeNormalCell(at: indexPath)
        }
    }
}

extension TableViewController {
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        if let largeRow = largeRow {
            if largeRow == indexPath {
                self.largeRow = nil
                tableView.reloadRows(at: [indexPath], with: .fade)
            } else {
                self.largeRow = indexPath
                tableView.reloadRows(at: [largeRow, indexPath], with: .fade)
            }
        } else {
            self.largeRow = indexPath
            tableView.reloadRows(at: [indexPath], with: .fade)
        }
    }
}

Upvotes: 1

Related Questions