【转】UITableViewCell自适应高度 UILabel自适应高度和自动换行
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// 列寬
CGFloat contentWidth = self.tableView.frame.size.width;
// 用何種字體進行顯示
UIFont *font = [UIFont systemFontOfSize:13];
// 該行要顯示的內容
NSString *content = [data objectAtIndex:indexPath.row];
// 計算出顯示完內容需要的最小尺寸
CGSize size = [content sizeWithFont:font constrainedToSize:CGSizeMake(contentWidth, 1000) lineBreakMode:UILineBreakModeWordWrap];
// 這裏返回需要的高度
return size.height;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
// 列寬
CGFloat contentWidth = self.tableView.frame.size.width;
// 用何種字體進行顯示
UIFont *font = [UIFont systemFontOfSize:13];
// 該行要顯示的內容
NSString *content = [data objectAtIndex:indexPath.row];
// 計算出顯示完內容需要的最小尺寸
CGSize size = [content sizeWithFont:font constrainedToSize:CGSizeMake(contentWidth, 1000) lineBreakMode:UILineBreakModeWordWrap];
// 構建顯示行
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
CGRect rect = [cell.textLabel textRectForBounds:cell.textLabel.frame limitedToNumberOfLines:0];
// 設置顯示榘形大小
rect.size = size;
// 重置列文本區域
cell.textLabel.frame = rect;
cell.textLabel.text = content;
// 設置自動換行(重要)
cell.textLabel.numberOfLines = 0;
// 設置顯示字體(一定要和之前計算時使用字體一至)
cell.textLabel.font = font;
return cell;
}
本文转自http://mrjeye.iteye.com/blog/1045785
文章来源:http://blog.csdn.net/csj1987/article/details/6662852
- //初始化label
- UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,0,0)];
- //设置自动行数与字符换行
- [label setNumberOfLines:0];
- label.lineBreakMode = UILineBreakModeWordWrap;
- // 测试字串
- NSString *s = @"这是一个测试!!!adsfsaf时发生发勿忘我勿忘我勿忘我勿忘我勿忘我阿阿阿阿阿阿阿阿阿阿阿阿阿啊00000000阿什顿。。。";
- UIFont *font = [UIFont fontWithName:@"Arial" size:12];
- //设置一个行高上限
- CGSize size = CGSizeMake(320,2000);
- //计算实际frame大小,并将label的frame变成实际大小
- CGSize labelsize = [s sizeWithFont:font constrainedToSize:size lineBreakMode:UILineBreakModeWordWrap];
- [label setFrame:CGRectMake:(0,0, labelsize.width, labelsize.height)];
最新文章
- css初始化
- VIM编辑器之常用命令
- Mysql占用过高CPU时的优化手段
- mysql基础语法及拓展到web中的sql注入
- Android应用程序窗口(Activity)的窗口对象(Window)的创建过程分析(转)
- PowerDesigner更改数据库类型
- C与Python变量的区别
- cogs 自己出的题目 题解报告
- 团体程序设计天梯赛-练习集L1-020. 帅到没朋友
- win8.1远程连接Redis数据库
- SparseArray,SparseBooleanArray和SparseIntArray
- VSCode python 遇到的问题:vscode can&#39;t open file &#39;<;unprintable file name>;&#39;: [Errno 2] No such file or directory
- Powerdesigner逆向工程64位Oracle数据库
- DirectX11 With Windows SDK--22 立方体映射:静态天空盒的读取与实现
- Spring AOP 切点(pointcut)表达式
- 在同时满足if 和 else 条件的情况下,输出所需的内容。
- 从零开始学 Web 系列教程
- TensorFlow --playground游乐场
- Oracle 导入导出报错的简单处理
- WordPress基础:极简手动安装教程