UILabel动态宽度,单元格上有sizeToFit

时间:2013-07-22 12:22:54

标签: iphone uitableview uilabel sizetofit

UITableViewCell内有UILabel个自定义Storyboard。我动态设置了这个UILabel的文字,我需要相应地调整UILabel的宽度,因为之后我还有另一个UILabel必须保持一致。

我正在尝试

> MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
> author = @"Some dynamic text";
> cell.authorLabel.text = author;
> [cell.authorLabel sizeToFit];

会发生什么: 在第一次渲染时,UILabel只保留storyboard上设置的宽度,因此文本被裁剪或后面有太多空格。

滚动后,单元格会出列并正确应用sizeToFit方法,但为时已晚,因为第二个UILabel已经位于错误的位置。 (由于声誉受限制不能发布图片)

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

也许你的意思是这样的:

MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
author = @"Some dynamic text";
cell.authorLabel.text = author; <-- excluded in your code
[cell.authorLabel sizeToFit];

如果这不起作用,请尝试使用以下内容:

子类UITableViewCell并重写下面的方法:

- (void)setSelected:(BOOL) selected
{ 
    [super setSelected:selected];
    [self.authorLabel sizeToFit];
}

答案 1 :(得分:1)

使用这个获得动态高度和宽度,

CGSize sizeDynamic  = [str sizeWithFont:[UIFont fontWithName:@"Arial-BoldMT" size:14] constrainedToSize:CGSizeMake(CGFLOAT_MAX,CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];

你可以得到,

sizeDynamic.height and sizeDynamic.width values
相关问题