转载自:
动态计算UITableViewCell高度详解
不知道大家有没有发现,在iOS APP开发过程中,UITableView是我们显示内容常见的控件,本人觉得它是UIKit中最复杂的一个控件。今天要向大家介绍的就是如何动态计算UITableViewCell高度的一经验与技巧,在此做一些总结方便朋友们查阅。为了不让讲解空洞抽象,我还是用代码实例的方式进行讲解,这样更容易接收与学习。
本文将介绍四种情况下UITableViewCell的计算方式,分别是:
1. Auto Layout with UILabel in UITableViewCell
2. Auto Layout with UITextView in UITableViewCell
3. Manual Layout with UILabel in UITableViewCell
4. Manual Layout with UITextView in UITableViewCell
5. 随UITextView高度动态改变Cell高度
首先创建一个Single Page的工程,我命名为CellHeightDemo
1. Auto Layout with UILabel in UITableViewCell
创建一个空的xib,命名为C1.xib, 然后拖入一个UITableViewCell控件。接着创建一个UITableViewCell的子类,命名为C1类。然后在C1.xib中,将与C1类进行关联。别给我说你不会关联,如果不会那看下图你就明白了。
只需要在Class那里写入关联的类名C1即可。
还有由于UITableViewCell需要重用功能,所以我们还需要设置一个重用标识
在Identifier那里写入重用标识C1,当然你也可以用任意字符。不过后面代码里需要这个字符。
接着我们来布局。用到了auto layout, 在此我不想介绍auto layout, 以后有时间再专门介绍,下图就是我布局
这儿有两点需要说明:1. UILabel的属性Lines这儿设为了0表示显示多行。2. Auto Layout一定要建立完完整。
接着我们在UITableView中来使用我们自定义的UITableViewCell C1。
首先我们创建一个UITableViewController的子类T1ViewController, 接着在Main.storyboard中拖入一个UITableViewController,并关联T1ViewController。
一切都准备好了,那我们现在来写点代码,给UITableView加点料。
我们想要我们的UITableView使用C1.xib中自定义的Cell,那么我们需要向UITableView进行注册。
UINib *cellNib = [UINib nibWithNibName:@"C1" bundle:nil];
[self.tableView registerNib:cellNib forCellReuseIdentifier:@"C1"];
这样就进行注册了,接着我们还需要每行显示的数据,为了简单一点,我就声明了一个NSArray变量来存放数据。
self.tableData = @[@"1\n2\n3\n4\n5\n6", @"123456789012345678901234567890", @"1\n2", @"1\n2\n3", @"1"];
现在实现UITableViewDataSource的protocol:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.tableData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
C1 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"C1"];
cell.t.text = [self.tableData objectAtIndex:indexPath.row];
return cell;
}
从self.tableData中的数据我们可以看到,每一个Cell显示的数据高度是不一样的,那么我们需要动态计算Cell的高度。由于是auto layout,所以我们需要用到一个新的API systemLayoutSizeFittingSize:来计算UITableViewCell所占空间高度。Cell的高度是在- (CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath这个UITableViewDelegate的方法里面传给UITableView的。
这里有一个需要特别注意的问题,也是效率问题。UITableView是一次性计算完所有Cell的高度,如果有1W个Cell,那么- (CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath就会触发1W次,然后才显示内容。不过在iOS7以后,提供了一个新方法可以避免这1W次调用,它就是- (CGFloat)tableView:(UITableView )tableView estimatedHeightForRowAtIndexPath:(NSIndexPath )indexPath。要求返回一个Cell的估计值,实现了这个方法,那只有显示的Cell才会触发计算高度的protocol. 由于systemLayoutSizeFittingSize需要cell的一个实例才能计算,所以这儿用一个成员变量存一个Cell的实列,这样就不需要每次计算Cell高度的时候去动态生成一个Cell实例,这样即方便也高效也少用内存,可谓一举三得。
我们声明一个存计算Cell高度的实例变量:
@property (nonatomic, strong) UITableViewCell *prototypeCell;
然后初始化它:
self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:@"C1"];
下面是计算Cell高度的实现:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
C1 *cell = (C1 *)self.prototypeCell;
cell.t.text = [self.tableData objectAtIndex:indexPath.row];
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
NSLog(@"h=%f", size.height + 1);
return 1 + size.height;
}
看了代码,可能你有点疑问,为何这儿要加1呢?笔者告诉你,如果不加1,结果就是错误的,Cell中UILabel将显示不正确。原因就是因为这行代码CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];由于是在cell.contentView上调用这个方法,那么返回的值将是contentView的高度,UITableViewCell的高度要比它的contentView要高1,也就是它的分隔线的高度。如果你不相信,那请看C1.xib的属性,比较下面两张图。
发现没Cell的高度是127, 面contentView的高度是126, 这下明白了吧。
为了让读者看清楚,我将Cell中UILabel的背景色充为了light gray.下面是运行效果:
2. Auto Layout with UITextView in UITableViewCell
本小段教程将介绍UITextView在cell中计算高度需要注意的地方。同样参考上面我们创建一个C2.xib, UITableViewCell的子类C2,并关联C2.xib与C2类。并在C2.xib中对其布局,同样使用了auto layout. 布局如下图:
创始UITableViewController的了类T2ViewController,在Main.storyboard中拖入UITableViewController,并关联他们。接着代码中注册C2.xib到UITableView.
下面计是计算高度的代码:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
C2 *cell = (C2 *)self.prototypeCell;
cell.t.text = [self.tableData objectAtIndex:indexPath.row];
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
CGSize textViewSize = [cell.t sizeThatFits:CGSizeMake(cell.t.frame.size.width, FLT_MAX)];
CGFloat h = size.height + textViewSize.height;
h = h > 89 ? h : 89; //89是图片显示的最低高度, 见xib
NSLog(@"h=%f", h);
return 1 + h;
}
在这儿我们是通过sizeThatFits:计算的UITextView的高度(这是计算UITextView内容全部显示时的方法,在第四小段中我们还会用到它),然后加上systemLayoutSizeFittingSize:返回的高度。为什么要这样呢? 因为UITextView内容的高度不会影响systemLayoutSizeFittingSize计算。这句话什么意思呢?我真不知道如何用言语表达了。还是先上一张图吧:
此图中距顶的约束是10, 距底的约束8, 距左边约束是87,距右边的约束是13, 那么systemLayoutSizeFittingSize:返回的CGSize为height等于19, size等于100. 它UITextView的frame是不影响systemLayoutSizeFittingSize:的计算。不知道这样说大家明白没。
所以,我们需要加上textViewSize.height.
3. Manual Layout with UILabel in UITableViewCell
本小段教程将介绍UILabel在Manual layout cell中计算高度, 原理是根据字体与字符串长度来计算长度与宽度。 按照前面介绍的,我们需要创建C3.xib, C3类, T3ViewController类,Main.storyboard中拖入UITableViewController,并分别建立关联。 为了简单,C3.xib中我就不加padding之类的了,如图
记得关闭C3.xib的auto layout
直接上代码了:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
C3 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"C3"];
cell.t.text = [self.tableData objectAtIndex:indexPath.row];
[cell.t sizeToFit];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
C3 *cell = (C3 *)self.prototypeCell;
NSString *str = [self.tableData objectAtIndex:indexPath.row];
cell.t.text = str;
CGSize s = [str calculateSize:CGSizeMake(cell.t.frame.size.width, FLT_MAX) font:cell.t.font];
CGFloat defaultHeight = cell.contentView.frame.size.height;
CGFloat height = s.height > defaultHeight ? s.height : defaultHeight;
NSLog(@"h=%f", height);
return 1 + height;
}
这儿用到了一个NSString的Cagetory方法:
- (CGSize)calculateSize:(CGSize)size font:(UIFont *)font {
CGSize expectedLabelSize = CGSizeZero;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
expectedLabelSize = [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size;
}
else {
expectedLabelSize = [self sizeWithFont:font
constrainedToSize:size
lineBreakMode:NSLineBreakByWordWrapping];
}
return CGSizeMake(ceil(expectedLabelSize.width), ceil(expectedLabelSize.height));
}
原理上面我已说了,这儿没有什么好说明的,代码一目了然。
4. Manual Layout with UITextView in UITableViewCell
本小段教程将介绍UITextView在Manual layout cell中计算高度, 原理是与第二小节里的相同,用sizeThatFits:的方法计算UITextView的长度与高度。然后加上padding就是Cell的高度。 按照前面介绍的,我们需要创建C4.xib, C4类, T4ViewController类,Main.storyboard中拖入UITableViewController,并分别建立关联。 为了简单,C4.xib中我就不加padding之类的了,如图
也直接上代码了,直观明了:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
C4 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"C4"];
cell.t.text = [self.tableData objectAtIndex:indexPath.row];
[cell.t sizeToFit];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
C4 *cell = (C4 *)self.prototypeCell;
NSString *str = [self.tableData objectAtIndex:indexPath.row];
cell.t.text = str;
CGSize s = [cell.t sizeThatFits:CGSizeMake(cell.t.frame.size.width, FLT_MAX)];
CGFloat defaultHeight = cell.contentView.frame.size.height;
CGFloat height = s.height > defaultHeight ? s.height : defaultHeight;
return 1 + height;
}
5. 随UITextView高度动态改变Cell高度
本小节要介绍的一个功能是,UITextView中UITableViewCell中,当输入UITextView中的字变多/变少时,高度变化,Cell高度与随之变化的功能。
按照前面介绍的,我们需要创建C5.xib, C5类, T5ViewController类,Main.storyboard中拖入UITableViewController,并分别建立关联。 为了简单,C5.xib中我就不加padding之类的了,如图
先看代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
C5 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"C5"];
cell.t.text = @"123";
cell.t.delegate = self;
return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
C5 *cell = (C5 *)self.prototypeCell;
cell.t.text = self.updatedStr;
CGSize s = [cell.t sizeThatFits:CGSizeMake(cell.t.frame.size.width, FLT_MAX)];
CGFloat defaultHeight = cell.contentView.frame.size.height;
CGFloat height = s.height > defaultHeight ? s.height : defaultHeight;
return 1 + height;
}
#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if ([text isEqualToString:@"\n"]) {
NSLog(@"h=%f", textView.contentSize.height);
}
return YES;
}
- (void)textViewDidChange:(UITextView *)textView {
self.updatedStr = textView.text;
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
原理就是UITextView内容改变的时候,计算自身高度,然后通知UITableView更新,这样就会触发UITableViewCell高度重新计算,以达到目的。
本文只是简单的介绍了一些原理与技巧,细节之处还请参看源码
参考:
也可以参考此处
Using Auto Layout in UITableView for dynamic cell layouts & variable row heights
TL;DR: Don’t like reading? Jump straight to the sample projects on GitHub:
Conceptual Description
The first 2 steps below are applicable regardless of which iOS versions you are developing for.
**1. Set Up & Add Constraint**s
In your UITableViewCell subclass, add constraints so that the subviews of the cell have their edges pinned to the edges of the cell’s contentView (most importantly to the top AND bottom edges). NOTE: don’t pin subviews to the cell itself; only to the cell’s contentView! Let the intrinsic content size of these subviews drive the height of the table view cell’s content view by making sure the content compression resistance and content hugging constraints in the vertical dimension for each subview are not being overridden by higher-priority constraints you have added. (Huh? Click here.)
Remember, the idea is to have the cell’s subviews connected vertically to the cell’s content view so that they can “exert pressure” and make the content view expand to fit them. Using an example cell with a few subviews, here is a visual illustration of what some (not all!) of your constraints would need to look like:
Example illustration of constraints on a table view cell.
You can imagine that as more text is added to the multi-line body label in the example cell above, it will need to grow vertically to fit the text, which will effectively force the cell to grow in height. (Of course, you need to get the constraints right in order for this to work correctly!)
Getting your constraints right is definitely the hardest and most important part of getting dynamic cell heights working with Auto Layout. If you make a mistake here, it could prevent everything else from working – so take your time! I recommend setting up your constraints in code because you know exactly which constraints are being added where, and it’s a lot easier to debug when things go wrong. Adding constraints in code is just as easy as and significantly more powerful than Interface Builder when you leverage one of the fantastic open source APIs available – here is the one I design, maintain, and use exclusively: https://github.com/smileyborg/PureLayout
2. Determine Unique Table View Cell Reuse Identifiers
For every unique set of constraints in the cell, use a unique cell reuse identifier. In other words, if your cells have more than one unique layout, each unique layout should receive its own reuse identifier. (A good hint that you need to use a new reuse identifier is when your cell variant has a different number of subviews, or the subviews are arranged in a distinct fashion.)
For example, if you were displaying an email message in each cell, you might have 4 unique layouts: messages with just a subject, messages with a subject and a body, messages with a subject and a photo attachment, and messages with a subject, body, and photo attachment. Each layout has completely different constraints required to achieve it, so once the cell is initialized and the constraints are added for one of these cell types, the cell should get a unique reuse identifier specific to that cell type. This means when you dequeue a cell for reuse, the constraints have already been added and are ready to go for that cell type.
Note that due to differences in intrinsic content size, cells with the same constraints (type) may still have varying heights! Don’t confuse fundamentally different layouts (different constraints) with different calculated view frames (solved from identical constraints) due to different sizes of content.
For iOS 8 - Self-Sizing Cells
3. Enable Row Height Estimation
With iOS 8, Apple has internalized much of the work that previously had to be implemented by you prior to iOS 8. In order to allow the self-sizing cell mechanism to work, you must first set the rowHeight property on the table view to the constant UITableViewAutomaticDimension. Then, you simply need to enable row height estimation by setting the table view’s estimatedRowHeight property to a nonzero value, for example:
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 44.0; // set to whatever your "average" cell height is
What this does is provide the table view with a temporary estimate/placeholder for the row heights of cells that are not yet onscreen. Then, when these cells are about to scroll onscreen, the actual row height will be calculated. To determine the actual height for each row, the table view automatically asks each cell what height its contentView needs to be based on the known fixed width of the content view (which is based on the table view’s width, minus any additional things like a section index or accessory view) and the auto layout constraints you have added to the cell’s content view and subviews. Once this actual cell height has been determined, the old estimated height for the row is updated with the new actual height (and any adjustments to the table view’s contentSize/contentOffset are made as needed for you).
Generally speaking, the estimate you provide doesn’t have to be very accurate – it is only used to correctly size the scroll indicator in the table view, and the table view does a good job of adjusting the scroll indicator for incorrect estimates as you scroll cells onscreen. You should set the estimatedRowHeight property on the table view (in viewDidLoad or similar) to a constant value that is the “average” row height. Only if your row heights have extreme variability (e.g. differ by an order of magnitude) and you notice the scroll indicator “jumping” as you scroll should you bother implementing tableView:estimatedHeightForRowAtIndexPath: to do the minimal calculation required to return a more accurate estimate for each row.
For iOS 7 support (implementing auto cell sizing yourself)
3. Do a Layout Pass & Get The Cell Height
First, instantiate an offscreen instance of a table view cell, one instance for each reuse identifier, that is used strictly for height calculations. (Offscreen meaning the cell reference is stored in a property/ivar on the view controller and never returned from tableView:cellForRowAtIndexPath: for the table view to actually render onscreen.) Next, the cell must be configured with the exact content (e.g. text, images, etc) that it would hold if it were to be displayed in the table view.
Then, force the cell to immediately layout its subviews, and then use the systemLayoutSizeFittingSize: method on the UITableViewCell’s contentView to find out what the required height of the cell is. Use UILayoutFittingCompressedSize to get the smallest size required to fit all the contents of the cell. The height can then be returned from the tableView:heightForRowAtIndexPath: delegate method.
4. Use Estimated Row Heights
If your table view has more than a couple dozen rows in it, you will find that doing the Auto Layout constraint solving can quickly bog down the main thread when first loading the table view, as tableView:heightForRowAtIndexPath: is called on each and every row upon first load (in order to calculate the size of the scroll indicator).
As of iOS 7, you can (and absolutely should) use the estimatedRowHeight property on the table view. What this does is provide the table view with a temporary estimate/placeholder for the row heights of cells that are not yet onscreen. Then, when these cells are about to scroll onscreen, the actual row height will be calculated (by calling tableView:heightForRowAtIndexPath:), and the estimated height updated with the actual one.
Generally speaking, the estimate you provide doesn’t have to be very accurate – it is only used to correctly size the scroll indicator in the table view, and the table view does a good job of adjusting the scroll indicator for incorrect estimates as you scroll cells onscreen. You should set the estimatedRowHeight property on the table view (in viewDidLoad or similar) to a constant value that is the “average” row height. Only if your row heights have extreme variability (e.g. differ by an order of magnitude) and you notice the scroll indicator “jumping” as you scroll should you bother implementing tableView:estimatedHeightForRowAtIndexPath: to do the minimal calculation required to return a more accurate estimate for each row.
5. (If Needed) Add Row Height Caching
If you’ve done all the above and are still finding that performance is unacceptably slow when doing the constraint solving in tableView:heightForRowAtIndexPath:, you’ll unfortunately need to implement some caching for cell heights. (This is the approach suggested by Apple’s engineers.) The general idea is to let the Auto Layout engine solve the constraints the first time, then cache the calculated height for that cell and use the cached value for all future requests for that cell’s height. The trick of course is to make sure you clear the cached height for a cell when anything happens that could cause the cell’s height to change – primarily, this would be when that cell’s content changes or when other important events occur (like the user adjusting the Dynamic Type text size slider).
iOS 7 Generic Sample Code (with lots of juicy comments)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Determine which reuse identifier should be used for the cell at this index path,
// depending on the particular layout required (you may have just one, or may have many).
NSString *reuseIdentifier = ...;
// Dequeue a cell for the reuse identifier.
// Note that this method will init and return a new cell if there isn't one available in the reuse pool,
// so either way after this line of code you will have a cell with the correct constraints ready to go.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
// Configure the cell with content for the given indexPath, for example:
// cell.textLabel.text = someTextForThisCell;
// ...
// Make sure the constraints have been set up for this cell, since it may have just been created from scratch.
// Use the following lines, assuming you are setting up constraints from within the cell's updateConstraints method:
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
// If you are using multi-line UILabels, don't forget that the preferredMaxLayoutWidth needs to be set correctly.
// Do it at this point if you are NOT doing it within the UITableViewCell subclass -[layoutSubviews] method.
// For example:
// cell.multiLineLabel.preferredMaxLayoutWidth = CGRectGetWidth(tableView.bounds);
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Determine which reuse identifier should be used for the cell at this index path.
NSString *reuseIdentifier = ...;
// Use a dictionary of offscreen cells to get a cell for the reuse identifier, creating a cell and storing
// it in the dictionary if one hasn't already been added for the reuse identifier.
// WARNING: Don't call the table view's dequeueReusableCellWithIdentifier: method here because this will result
// in a memory leak as the cell is created but never returned from the tableView:cellForRowAtIndexPath: method!
UITableViewCell *cell = [self.offscreenCells objectForKey:reuseIdentifier];
if (!cell) {
cell = [[YourTableViewCellClass alloc] init];
[self.offscreenCells setObject:cell forKey:reuseIdentifier];
}
// Configure the cell with content for the given indexPath, for example:
// cell.textLabel.text = someTextForThisCell;
// ...
// Make sure the constraints have been set up for this cell, since it may have just been created from scratch.
// Use the following lines, assuming you are setting up constraints from within the cell's updateConstraints method:
[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];
// Set the width of the cell to match the width of the table view. This is important so that we'll get the
// correct cell height for different table view widths if the cell's height depends on its width (due to
// multi-line UILabels word wrapping, etc). We don't need to do this above in -[tableView:cellForRowAtIndexPath]
// because it happens automatically when the cell is used in the table view.
// Also note, the final width of the cell may not be the width of the table view in some cases, for example when a
// section index is displayed along the right side of the table view. You must account for the reduced cell width.
cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds));
// Do the layout pass on the cell, which will calculate the frames for all the views based on the constraints.
// (Note that you must set the preferredMaxLayoutWidth on multi-line UILabels inside the -[layoutSubviews] method
// of the UITableViewCell subclass, or do it manually at this point before the below 2 lines!)
[cell setNeedsLayout];
[cell layoutIfNeeded];
// Get the actual height required for the cell's contentView
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
// Add an extra point to the height to account for the cell separator, which is added between the bottom
// of the cell's contentView and the bottom of the table view cell.
height += 1.0f;
return height;
}
// NOTE: Set the table view's estimatedRowHeight property instead of implementing the below method, UNLESS
// you have extreme variability in your row heights and you notice the scroll indicator "jumping" as you scroll.
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Do the minimal calculations required to be able to return an estimated row height that's
// within an order of magnitude of the actual height.
// For example:
if ([self isTallCellAtIndexPath:indexPath]) {
return 350.0f;
} else {
return 40.0f;
}
}
Sample Projects
Feel free to raise any questions or issues you run into (you can open issues on GitHub or post comments here). I’ll try my best to help!
Xamarin (C#/.NET)
If you’re using Xamarin, check out this sample project put together by @KentBoogaart.
raywenderlich上的文章
Dynamic Table View Cell Height and Auto Layout
原理与其他的类似,稍有不同
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return [self heightForBasicCellAtIndexPath:indexPath];
}
- (CGFloat)heightForBasicCellAtIndexPath:(NSIndexPath *)indexPath {
static RWBasicCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [self.tableView dequeueReusableCellWithIdentifier:RWBasicCellIdentifier];
});
[self configureBasicCell:sizingCell atIndexPath:indexPath];
return [self calculateHeightForConfiguredSizingCell:sizingCell];
}
- (CGFloat)calculateHeightForConfiguredSizingCell:(UITableViewCell *)sizingCell {
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height + 1.0f; // Add 1.0f for the cell separator height
}
Understanding Self Sizing Cells and Dynamic Type in iOS 8
在iOS8以前,如果你想要在tableView中展示不同高度的动态的内容,你需要手动来计算行高。在iOS8中,Self Sizing Cell为展示动态内容提供了解决方案。简单来说,使用Self Sizing Cell要这样做:
设置tableView的rowHeight为UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension
Self-sizing Table View Cells