UITableViewCell with dynamic height iOS

前端 未结 12 2351
日久生厌
日久生厌 2020-11-27 17:54

I have implemented TableView with CustomCell in my app,

I want dynamic height of my UITableViewCell according to text length in UITableViewCell

12条回答
  •  萌比男神i
    2020-11-27 18:53

    I saw a lot of solutions but all was wrong or uncomplet. You can solve all problems with 5 lines in viewDidLoad and autolayout. This for objetive C:

    _tableView.delegate = self;
    _tableView.dataSource = self;
    self.tableView.estimatedRowHeight = 80;//the estimatedRowHeight but if is more this autoincremented with autolayout
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    [self.tableView setNeedsLayout];
    [self.tableView layoutIfNeeded];
    self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) ;
    

    For swift 2.0:

     self.tableView.estimatedRowHeight = 80
     self.tableView.rowHeight = UITableViewAutomaticDimension      
     self.tableView.setNeedsLayout()
     self.tableView.layoutIfNeeded()
     self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0)
    

    Now create your cell with xib or into tableview in your Storyboard With this you no need implement nothing more or override. (Don forget number os lines 0) and the bottom label (constrain) downgrade "Content Hugging Priority -- Vertical to 250"

    You can donwload the code in the next url: https://github.com/jposes22/exampleTableCellCustomHeight

    References: http://candycode.io/automatically-resizing-uitableviewcells-with-dynamic-text-height-using-auto-layout/

提交回复
热议问题