2

I am working on a project in swift which needs the cell size to be dynamic according to the label content, so i searched for dynamic cell height, i found some solution but all of it included use of storyboard for assigning constrain. Is it possible to do it without storyboard. Is it possible to do it programatically? I mean applying self sizing without storyboard

my code is:

class a: UITableViewDelegate, UITableViewDataSource {
    tableView = UITableView(frame: CGRectMake(0, 0, self.view.frame.width, self.view.frame.height), style: UITableViewStyle.Plain)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.estimatedRowHeight = 100
    tableView.rowHeight = UITableViewAutomaticDimension
    self.view.addSubview(tableView)
}

Hope the question is clear.

Thanks in advance.

Edit: None of the answers below is helpful

user2413621
  • 2,916
  • 7
  • 24
  • 28

5 Answers5

1

Try this method.

 override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
 return // get cell text label high and return +10 or +20 height. what is label height..
}
yogesh wadhwa
  • 711
  • 8
  • 16
1

You can try this method.

func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
 self.dashBoardTableView.rowHeight = UITableViewAutomaticDimension

    if (CellIdentifier == "dashBoardTableCellID")
    {
       dashBoardTableView.rowHeight =  96
    }
    else
    {
        dashBoardTableView.rowHeight =  60
    }

    return self.dashBoardTableView.rowHeight
}
Alvin George
  • 14,148
  • 92
  • 64
0

Yes you can, you can create your constraints in code. I suggest you look at the class NSLayoutConstraint:

NSLayoutConstraint Apple documentation

Khaled Barazi
  • 8,681
  • 6
  • 42
  • 62
0

iOS 8 suppoorts self sized tableview cells. To enable it first create your cell with correct constraints. End use code below

tableView.estimatedRowHeight = 50
tableView.cellHeight = UITableViewCellAutomaticDimension

estimatedRowHeight is just hint for tableview. When tableview reuses cells it looks its content and adjust sizes acoording to it.

mustafa
  • 15,254
  • 10
  • 48
  • 57