Joe Dodge Joe Dodge - 3 months ago 9
Swift Question

Wondering if this is the best way to execute this. tableview switching cell sizes

I have a tableview with two prototype cells that share identical information. When i tap the "CardList" button all the cells go from one cell size to a smaller size and then vice versa when i tap it again. the first transition works fine but going back from the smaller cell to the larger one the, the cells height is only about 50 pts instead of the 338 that i have set. Also, wondering if this is the best way to do this by having two different cells. Should i just have one cell and rearrange it?

var CellSize = Int()

@IBAction func CardList(sender: AnyObject){

if (sender.titleLabel!?.text == "Card")

{
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 338
self.CellSize = 2
self.tableView.reloadData()
sender.setTitle("List", forState: UIControlState.Normal);
}
else
{
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 142
self.CellSize = 1
self.tableView.reloadData()
sender.setTitle("Card", forState: UIControlState.Normal);
}
}


////////////////

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

if CellSize == 1 {

let cell = self.tableView.dequeueReusableCellWithIdentifier(
"ResultsCell2", forIndexPath: indexPath)
as! ResultsCell2

let row = indexPath.row
cell.Name.text = Names[row]
cell.Image.image = UIImage(named: Images[row])
cell.Price.text = Prices[row]
return cell

}
else
{
let cell2 =
self.tableView.dequeueReusableCellWithIdentifier(
"ResultsCell", forIndexPath: indexPath)
as! ResultsCell

let row = indexPath.row
cell2.Name.text = Names[row]
cell2.Image.image = UIImage(named: Images[row])
cell2.Price.text = Prices[row]

return cell2
}
}

Answer

Well to set a cellRow's height in a proper way you should use this method:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
{
    if CellSize == 1 {
        return 338
    }
    return 50
}

Note: UITableViewDelegate method and to be able to use it you should set your tableView's delegate to your own class and call this method there.