Ada*_*ite 24 iphone objective-c uitableview ios
我有一个UITableView填充了自定义单元格(继承自UITableViewCell),每个单元格包含一个UIWebView根据它的内容自动调整大小.这就是问题,如何UITableView根据内容(变量webView)更改单元格的高度.
解决方案必须是动态的,因为用于填充的HTML UIWebViews是从不断变化的Feed中解析的.
我有一种感觉,我需要使用UITableView委托方法,heightForRowAtIndexPath但从它的定义:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
;//This needs to be variable
}
Run Code Online (Sandbox Code Playgroud)
我无法访问单元格或其内容.我可以更改单元格的高度cellForRowAtIndexPath吗?
任何帮助都会很棒.谢谢.
两年多前我问过这个问题.通过自动布局的介绍,可以找到iOS7的最佳解决方案:
在iOS8上,此功能内置于SDK中
San*_*aus 26
这通常很有效:
Objective-C的:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
Run Code Online (Sandbox Code Playgroud)
迅速:
override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
return UITableViewAutomaticDimension;
}
Run Code Online (Sandbox Code Playgroud)
小智 20
我发现动态高度的最佳方法是预先计算高度并将其存储在某种类型的集合中(可能是数组).假设单元格主要包含文本,您可以使用它-[NSString sizeWithFont:constrainedToSize:lineBreakMode:]来计算高度,然后返回相应的值heightForRowAtIndexPath:
[编辑]如果内容不断变化,您可以实现一种方法,在提供新数据时更新高度数组.
小智 6
self.tblVIew.estimatedRowHeight = 500.0; // put max you expect here.
self.tblVIew.rowHeight = UITableViewAutomaticDimension;
Run Code Online (Sandbox Code Playgroud)
我尝试了很多解决方案,但有一个解决方案是这个,由朋友建议:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
int height = [StringUtils findHeightForText:yourLabel havingWidth:yourWidth andFont:[UIFont systemFontOfSize:17.0f]];
height += [StringUtils findHeightForText:yourOtherLabel havingWidth:yourWidth andFont:[UIFont systemFontOfSize:14.0f]];
return height + CELL_SIZE_WITHOUT_LABELS; //important to know the size of your custom cell without the height of the variable labels
}
Run Code Online (Sandbox Code Playgroud)
StringUtils.h类:
#import <Foundation/Foundation.h>
@interface StringUtils : NSObject
+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font;
@end
Run Code Online (Sandbox Code Playgroud)
StringUtils.m类:
#import "StringUtils.h"
@implementation StringUtils
+ (CGFloat)findHeightForText:(NSString *)text havingWidth:(CGFloat)widthValue andFont:(UIFont *)font {
CGFloat result = font.pointSize+4;
if (text) {
CGSize size;
CGRect frame = [text boundingRectWithSize:CGSizeMake(widthValue, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:font}
context:nil];
size = CGSizeMake(frame.size.width, frame.size.height+1);
result = MAX(size.height, result); //At least one row
}
return result;
}
@end
Run Code Online (Sandbox Code Playgroud)
它对我来说很完美.我有一个自定义单元格,其中包含3个固定尺寸的图像,2个固定尺寸的标签和2个可变标签.工作就像一个魅力.希望它也适合你.
最好的问候,亚历山大.
| 归档时间: |
|
| 查看次数: |
57559 次 |
| 最近记录: |