发表:2013-03-26 14:26:35
UITableViewCell单元格通过tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath委托方法返回固定高度,要达到自动适应高度的单元格,只需要根据内容的高度动态改变该方法的返回值即可。 indexViewController.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #import <UIKit/UIKit.h>
#import "RefreshView.h"
#import "CustomCell.h"
#import "BaseViewController.h"
#import "IFTweetLabel.h"
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 10.0f
@interface IndexViewController : BaseViewController<UITableViewDataSource,UITableViewDelegate> {
NSArray *data_;
}
- ( void )refresh;
@property (assign,nonatomic) IBOutlet UITableView *tableView;
@end
|
indexViewController.m 单元格高度设置 1 2 3 4 5 6 7 8 9 10 11 12 | - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = [data_ objectAtIndex:[indexPath row]];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 44.0f);
return height + (CELL_CONTENT_MARGIN * 2)+30;
}
|
单元格 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *identifier=@ "mycell" ;
NSString *str=[data_ objectAtIndex:indexPath.row];
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
UILabel *label = nil;
NSString *text = str;
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
[label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))];
if (cell==nil) {
cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
];
}
return cell;
}
|
以上代码只适用于UITableViewCell为全文本的情况,如果非全文本,可以通过计算UILable控件的高度实现Cell所需要的高度。详情可参考:http:///blog/ceiba/Ios/20130330/610.html
|