UITableViewCell auto height based on amount of UILabel text

前端 未结 5 1366
终归单人心
终归单人心 2020-12-03 20:54

I have a bit of a tricky set up in my storyboard, I have a UIViewController that holds a UITableViewController. Within the UITableViewController I have several prototypecell

相关标签:
5条回答
  • 2020-12-03 21:38

    step1:Give below constraint to UIView that is inside to the contentView.

    • Leading constraint to contentView
    • Top constraint to contentView
    • Bottom constraint to contentView
    • Trailing constraint to contentView

    step2: Give below constraint to UIlabel

    • Leading constraint to UIImageView
    • Top constraint to UIView
    • Bottom constraint to UIView
    • Trailing constraint to UIView

    step3: Then select your Trailing constraint of IUlabel and select edit option and then select constant and select greaterThanEqual option.

    step4: set label's numberofline = 0

    step5: Add this code into viewDidLoad()

    yourtableview.estimatedRowHeight = 80.0
    yourtableview.rowHeight = UITableViewAutomaticDimension
    
    0 讨论(0)
  • 2020-12-03 21:38

    After populating the UILabel and applying constrains, get the height of the label and set it as the height of the UIView.

    After that call -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath and pass the height of the UILabel/UIView so that it gets the actual height for that row

    0 讨论(0)
  • 2020-12-03 21:44

    Use UITableViewAutomaticDimension

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 300
    
    0 讨论(0)
  • 2020-12-03 21:54

    To go a little further on Dao's answer..

    He is correct, you need to use UITableViewAutomaticDimension

    Also, you need to ensure that you setup your constraints in a way that all of the content in the cell is constrained to the cells contentView. So your label will likely need constraints such as

    • Leading constraint to ImageView
    • Top constraint to contentView
    • Bottom constraint to contentView
    • Trailing constraint to contentView

    Make sure that you set the UILabel to multiline (or lines = 0) and it should work.

    If you are using the heightForRowAt delegate functions ensure you return UITableViewAutomaticDimension

    0 讨论(0)
  • 2020-12-03 21:55

    Swift 4.2 and 5. As mention above you can set UITableView object property or

    tblView.rowHeight = UITableView.automaticDimension 
    tblView.estimatedRowHeight = 300
    

    you can also define the same by implementing UITableViewDelegate methods

    extension ViewController: UITableViewDelegate {
          func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
            return 300
          }
          func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return UITableView.automaticDimension
          }
        }
    
    0 讨论(0)
提交回复
热议问题