Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing height of individual cell UITableView

I would like something like the following:

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

    let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell", forIndexPath: indexPath) as! UITableViewCell

    if indexPath == 3{

        cell.height = "50dp"

    }       

    return cell

}

what is the alternative or the easiest way to go about this?

EDIT

Is it possible for me to also specify section number: i.e-

if sectionIndex == 5
like image 682
Greg Peckory Avatar asked Jul 01 '15 08:07

Greg Peckory


3 Answers

I suggest use the heightForRowAtIndexPath function. TableView will call this function to determine the row height for a specific indexpath.

Sample code:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.section == SECTION_INDEX {
        return 60
    } else {
        return UITableViewAutomaticDimension
    }
}

Swift 4:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.section == SECTION_INDEX {
        return 60
    } else {
        return UITableViewAutomaticDimension
    }
}

A little explain: indexPath have two properties: section and row. By checking these two properties, you can make your own control flow to determine the height for each cell.

If you return 60, it means you want the cell's height to be 60 points. If you return UITableViewAutomaticDimension, you want the system to decide the best height for you (in this case, you'd better set autolayout for the cell in storyboard).

I also suggest you take the stanford course CS193p on iTunes U, it would be of great help to you :)

like image 167
Zhu Shengqi Avatar answered Oct 04 '22 22:10

Zhu Shengqi


the easiest way is to override heightForRowAtIndexPath

  override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    let section = indexPath.section
    let row = indexPath.row
    if section == 0 && row == 2{
      return 50.0
    }
    return 22.0
  }
like image 32
vadian Avatar answered Oct 05 '22 00:10

vadian


func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
   if indexPath.section == 5
   {
       if indexPath.row == 3
       {
           return 150.0
       }
   }

   return 200.0
}
like image 4
Utsav Parikh Avatar answered Oct 04 '22 23:10

Utsav Parikh