The easiest way to achieve highly adaptive cell

First of all, the first step, the layout of the label whose height changes dynamically with the content in the custom cell is completed using the autolayout layout. There is a point to note here is that the distance between the label and the cell boundary must be determined, and the height of the label cannot be fixed. , and then set the label's numberOfLines=0. Setting the number of lines to 0 means that the label can have any line. 
Second, implement the following two methods in the tableview's delegate:

 

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath { return 10; }

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return UITableViewAutomaticDimension; }

Key point 1 : The estimatedHeightForRowAtIndexPath method must be rewritten. 
This method appeared after iOS7.0. If you do not rewrite this method and only rewrite heightForRowAtIndexPath, then you will find that the cell will not adapt to the height according to the content of the label. Because the system first obtains the height of the cell, and then obtains the view of the cell. That is, call heightForRowAtIndexPath first, and then call cellForRowAtIndexPath. Before cellForRowAtIndexPath is called, your label is not set with text content, so the height it gets is not what you want. Then we have to find a way to let the system get the height of the cell after getting the cell. The method is to rewrite estimatedHeightForRowAtIndexPath. As the name suggests, it will return an estimated height. With this method, tableview will call it first to get the estimated height, then get the cell, and finally get the real height. The return value of estimatedHeightForRowAtIndexPath can be arbitrary, and you can return as many as you want. It is just a comfort to the tableview, so that it can delay the acquisition of the real height. 
Key point 2 : The return value of the true height is 
UITableViewAutomaticDimension 
. Key point 3 : The elements in the cell must be laid out relative to the top and bottom of the cell, so that when the content in the element changes dynamically, the cell can be stretched

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324790169&siteId=291194637