Swift: How to set dynamic cell height in TableViewController which contains more than one cell

前端 未结 2 698
甜味超标
甜味超标 2021-01-15 06:44

I have a TableViewController, which contains three different customized cell. For the first cell, I want to contain a horizontal scrolled CollectionView, the second cell con

相关标签:
2条回答
  • 2021-01-15 07:28

    This is possible:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
        if indexPath.section == 0 {
    
            let cell = tableView.dequeueReusableCellWithIdentifier("TableViewCell1") as! HomePageTableViewCell1
    
            let string1 = "blablabla"
            let charCountString1 = string1.character.characters.count
    
            tableView.rowHeight = CGFloat(charCountString1)
            return cell
        }
    
         else if indexPath.section == 1 {
    
            let cell = tableView.dequeueReusableCellWithIdentifier("TableViewCell2") as! HomePageTableViewCell2
    
            let imageHeight = imageView.frame.height
    
            tableView.rowHeight = CGFloat(imageHeight)
            return cell
        }
         else {
    
            let cell = tableView.dequeueReusableCellWithIdentifier("TableViewCell3") as! HomePageTableViewCell3
    
            let string3 = "ldsakjfalksdjflk"
            let charCountString3 = string3.character.characters.count
    
            tableView.rowHeight = CGFloat(charCountString3)
            return cell
        }
    
    }
    
    0 讨论(0)
  • 2021-01-15 07:41

    you can always have the dynamic height for your tableView on the base of your content, no need to return the static height for just setup the constraints in your cell properly and always use preferred priority for content-hugging content-compressionResistance.

    in -viewDidLoad just set

    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 60; // or whatever is suitable for you 
    

    you can also have reference from the Ray Wenderlich's tutorial Self-sizing Table View Cells

    0 讨论(0)
提交回复
热议问题