[英]UITableView - getting the width of cells to fit text?
我正在编写一个自定义UITableViewCell对象,并实现了layoutSubviews
来在单元格内容更新时调整其大小。
为了实现heightForRowAtIndexPath
,我正在计算自定义UITableViewCell对象中单元格的高度。 我使用NSString sizeWithFont
基于UILabel中的文本和UITableView中单元格的宽度来计算单元格的大小。
但是,如何获取UITableView中单元格的宽度?
现在,我将表格视图传递给对象并使用框架。 但是宽度是整个表格的宽度,而不是单个单元格的宽度。 我在这里想念什么吗?
提前致谢。
编辑3
我在想,如果真的不可能,只需测试纵向或横向,然后手动设置宽度即可(ipad仅有两种不同的方向)。
编辑2
有人对“为什么要用xxxx这样做”提出了一些疑问。 我知道也许有一种更好的方法来实现自己的目标,即创建一个自定义单元格,该单元格可以根据不同的文本长度来计算其自身的高度。 如果有更好的方法可以做到,我全是:)
编辑
http://img845.imageshack.us/img845/7792/screenshot20121129at193.png
+ (CGFloat)getHeightForCellWithText:(NSString *)text isExpanded:(BOOL)expanded tableView:(UITableViewController *)tv {
ProposalViewCell *cell = [[ProposalViewCell alloc] initWithStyle:UITableViewCellSelectionStyleNone reuseIdentifier:@"NormalCell" tableView:tv];
[cell setLabelText:text];
[cell setExpanded:expanded];
[cell layoutSubviews];
return cell.primaryLabel.frame.size.height + cell.readmoreButton.frame.size.height + cell.sendmessageButton.frame.size.height +30;
}
- (void)layoutSubviews {
[super layoutSubviews];
_primaryLabel.numberOfLines = 0; // multiple lines
// size of expanded text label
// sizeWithFont: if text doesn't fit, it is truncated
CGSize expandedSize = [_primaryLabel.text sizeWithFont:myFont constrainedToSize:CGSizeMake(tableView.view.frame.size.width, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
// size as expanded by default
_primaryLabel.frame = CGRectMake(10, 10, expandedSize.width, expandedSize.height);
if (expanded==NO) {
// size of summary text label
_primaryLabel.numberOfLines = 10;
CGSize summarySize = [_primaryLabel sizeThatFits:_primaryLabel.frame.size];
_primaryLabel.frame = CGRectMake(10, 10, summarySize.width, summarySize.height);
}
_readmoreButton.frame = CGRectMake(10, _primaryLabel.frame.size.height+10, 225, 25);
_sendmessageButton.frame = CGRectMake(10, _primaryLabel.frame.size.height+10+_readmoreButton.frame.size.height+10, 225, 25);
}
要获取单元格的宽度,只需执行此操作...
cell.contentview.frame.size.width
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.