Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of tableViewCell line height calculation?

2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the "tableViewCell line height calculation processing method is what", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's train of thought slowly in-depth, together to study and learn "what is the tableViewCell line height calculation processing method?"

1. There is no need to dynamically calculate height

When I write tableview, it's basically custom cell, and all custom cell inherits a base class, BaseTableViewCell:

.h:

.h: / reuse logo + (NSString *) reuseIdentifier;// cell height + (CGFloat) staticHeight;.m:-(id) initWithStyle: (UITableViewCellStyle) style reuseIdentifier: (NSString *) reuseIdentifier {self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) {self.opaque = NO; self.selectionStyle = UITableViewCellSelectionStyleNone;} return self;} / / reuse logo + (NSString *) reuseIdentifier {return NSStringFromClass ([self class]);} / cell height + (CGFloat) staticHeight {return 44.f;}

The advantage of writing this is that when we use tableview, it makes it easier for us to use the reuse identifier line. Take a look at:

StaticHeight can change the settings in the custom cell of the subclass. When using:

If you write it this way, you can see the settings for each custom cell more clearly, and it will also make the code look elegant and tidy.

two。 Dynamic calculation height

In actual development, the most commonly used is to dynamically calculate the height of cell, which is also a very basic function of tableView.

For example, search for information:

The height of the title is not fixed, the height of the content is not fixed, and the label is not fixed, so you need to calculate the line height according to the content in the model:

When using it, set it in the proxy of tableview:

-(CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {WMSearchResultQAModel * model = self.dataArray [indexPath.row]; return [WMSearchResultQAModel calutWholeCellHeightWithModel:model];}

In this way, you can meet the different height requirements of each cell according to the content.

This method is cumbersome, but it is also the most accurate and controllable, supporting both autolayout and frame.

3. Dynamic calculation-cache height

Why cache height?

Because when the tableView scrolls, it will constantly call back the heightForRowAtIndexPath proxy method, when the height of the cell needs adaptive content, it means that the height has to be calculated every time the method is called back, and the calculation takes time. The embodiment of the user experience is stutter. It is well known that 60fps is more in line with the human eye. If the number of frames is less than this value, you will obviously feel the phenomenon such as jamming. In order to make the user experience better, we need to optimize the high computing.

Idea: in order to avoid repetitive and meaningless calculations of cell height, cache height is particularly important.

Cache height mechanism

Cache height We need a container to store the height value. Model can be a variable array or a variable dictionary, so that whenever we call back the heightForRowAtIndexPath method, we first go to the cache to fetch it. If there is any, we will directly take it out. If not, calculate the height and cache it.

Take model as an example:

Declare a cellHeight attribute in model to save the height of the Cell corresponding to the Model. Then in the heightForRowAtIndexPath method, if the cellHeight of the current Model is 0, which means that the Cell has not been cached, the height of the Cell is calculated and recorded in the Model, so that the next time you get the height of the Cell, you can directly obtain it from the Model without recalculating:

-(CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {WMSearchResultQAModel * model = self.dataArray [indexPath.row]; if (model.cellHeight > 0) {/ / height with cache, return model.cellHeight;} / / when there is no cache, calculate the height and cache CGFloat cellHeight; = [WMSearchResultQAModel calutWholeCellHeightWithModel:model]; / / cache it to model model.cellHeight = cellHeight; return cellHeight;}

In this way, we achieve the optimization corresponding to high cache and Model and Cell. We do not need to manage high cache manually. When adding and deleting data, we add or delete Model from the data source.

If you use a variable array or variable dictionary, you need to empty the tableView when it is refreshed.

4. Adaptive height

After iOS8, the system provides a dynamic settlement line height method UITableViewAutomaticDimension combined with autolayout. With good constraints, we do not have to implement the heightForRowAtIndexPath proxy method.

There is no pressure for masonry support.

Implementation steps:

1. TableView settings

/ / preset row height self.tableView.estimatedRowHeight = xxx;// automatically calculate row height mode self.tableView.rowHeight = UITableViewAutomaticDimension

2. In custom cell, masonry layout, such as:

-(void) layoutSubviews {[super layoutSubviews]; [self.headImgView mas_makeConstraints: ^ (MASConstraintMaker * make) {make.top.left.offset (kSpace15); make.size.mas_equalTo (CGSizeMake (50.f, 50.f)); / / make.bottom.equalTo (self.contentView.mas_bottom). Offset (- kSpace15) to be added in automatic row height mode;}] [self.nickNameLabel mas_makeConstraints: ^ (MASConstraintMaker * make) {make.left.equalTo (self.headImgView.mas_right) .offset (12.f); make.top.offset (17.f);}]; [self.jobWorkLabel mas_makeConstraints: ^ (MASConstraintMaker * make) {make.left.equalTo (self.nickNameLabel.mas_right) .offset (8.f); make.right.lessThanOrEqualTo (self.contentView.mas_right). Offset (- kSpace15); make.top.offset (21.f);}] [self.hospitalLabel mas_makeConstraints: ^ (MASConstraintMaker * make) {make.left.equalTo (self.headImgView.mas_right) .offset (12.f); make.top.equalTo (self.jobWorkLabel.mas_bottom) .offset (6.f);}]; [self.line mas_makeConstraints: ^ (MASConstraintMaker * make) {make.left.right.bottom.offset (0); make.height.mas_equalTo (0.5f);}];}

There are two points to pay attention to when laying out:

All child controls rely on self.contentView as the constraint parent instead of self (cell)

Key controls need to be constrained by bottom (since row height is no longer specified, constraints based on bottom need to be given)

3. The most critical step: [cell layoutIfNeeded]

-(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {WMDoctorEvaluateDescribeInputCell * cell = [tableView dequeueReusableCellWithIdentifier: [WMDoctorEvaluateDescribeInputCell reuseIdentifier] forIndexPath:indexPath]; kWeakSelf cell.describeInputBlock = ^ (NSString * _ Nonnull describeText) {weakSelf.inputDescribeText = describeText;}; / / the key step is to solve the problem of abnormal display [cell layoutIfNeeded]; return cell;}

This completes the automatic adaptation to the height requirements.

In addition:

For some cell that are difficult to adapt to height automatically, you can deal with them separately as follows:

-(CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {if (indexPath.section = = 2) {return [WMDoctorEvaluateStarCell staticHeight];} return UITableViewAutomaticDimension;}

5. Adaptive height-cache row height

In the use of UITableViewAutomaticDimension, some interfaces are more complex, although this can complete the display, but in the process of sliding, you can feel the stuck frame with the naked eye, it is well known that 60fps is more in line with the human eye, if the number of frames is lower than this value, you will obviously feel the phenomenon of stuck frame, which belongs to the problem of optimizing performance, so it is necessary to think about how to optimize tableview performance.

Train of thought:

Cache height mechanism

First get the actual height displayed by cell

-(void) tableView: (UITableView *) tableView didEndDisplayingCell: (UITableViewCell *) cell forRowAtIndexPath: (NSIndexPath *) indexPath {NSString * key = [NSString stringWithFormat:@ "% ld", (long) indexPath.row]; [self.heightDict setObject:@ (cell.height) forKey:key]; NSLOG (@ "the final height calculated for line% @ is% f", key,cell.height);}

/ / didEndDisplayingCell this method will be triggered when the cell slides out of the screen, and the cell has been really displayed on the screen, so the height printed here must be the most correct height. Highly cached in the dictionary according to indexPath.row as key.

Then determine in the heightForRowAtIndexPath method that if there is a value in the dictionary, the cache height is used, otherwise it is automatically calculated:

-(CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath {NSString * key = [NSString stringWithFormat:@ "% ld", indexPath.row]; if (self.heightDict [key]! = nil) {NSNumber * value = _ heightDict; return value.floatValue;} return UITableViewAutomaticDimension;}

Note: when setting the estimated height of cell, be sure to set the value of the minimum height cell. Otherwise, when sliding, when the height of the smallest one slides to more than half, it will suddenly disappear, resulting in the phenomenon of frame drop.

Thank you for your reading, the above is the content of "what is the method of tableViewCell line height calculation". After the study of this article, I believe you have a deeper understanding of what the method of tableViewCell line height calculation is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report