UILabels没有在UITableView中调整大小

时间:2013-05-23 19:32:37

标签: ios objective-c uilabel uitextview

我有一个使用原型单元格的UITableView。单元格有一个名为dataCell的自定义类。自定义单元格还有三个UILabel:idLabel,contLabel和expLabel。单元格根据expLabel中的文本数量正确调整大小;但是,我不能让标签本身调整大小。当我向下滚动时,一些标签会调整大小;但是,当我向上滚动时,它们还会恢复显示两行并省略文本。这是我的代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

dataCell *cell = (dataCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];


// the rest of your configure cell

// First Cell Label
[cell.idLabel setText:[idData objectAtIndex:indexPath.row]];
cell.idLabel.numberOfLines = 0;


// Second Cell Label
[cell.contLabel setText:[conData objectAtIndex:indexPath.row]];
cell.contLabel.numberOfLines = 0;



// Third Cell Label
[cell.expLabel setText:[expData objectAtIndex:indexPath.row]];
cell.expLabel.numberOfLines=0;
CGSize expectedLabelSize = [cell.expLabel.text sizeWithFont:cell.expLabel.font constrainedToSize:CGSizeMake(220, FLT_MAX) lineBreakMode:cell.expLabel.lineBreakMode];
cell.expLabel.frame=CGRectMake(cell.expLabel.frame.origin.x, cell.expLabel.frame.origin.y, expectedLabelSize.width, expectedLabelSize.height);




return cell;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
dataCell *cell = (dataCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
CGSize maximumLabelSize = CGSizeMake(220, FLT_MAX);
[cell.expLabel setText:[expData objectAtIndex:indexPath.row]];
CGSize expectedLabelSize = [cell.expLabel.text sizeWithFont:cell.expLabel.font constrainedToSize:maximumLabelSize lineBreakMode:cell.expLabel.lineBreakMode];
if (expectedLabelSize.height<43) {
    expectedLabelSize.height=43;
}

return expectedLabelSize.height;  }

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

如果您正在使用故事板和UITableViewCell,那么您只需更改自动调整大小屏幕,但如果您以编程方式执行此操作,则必须设置计算文本宽度和高度并重置标签的框架,

UILabel* label = [[UILabel alloc] init];
UIFont* font = label.font;
CGSize maxContentSizeForText = CGSizeMake(maxTextWidth, maxTextHeight);
CGSize stringTextSize = [string sizeWithFont:font constrainedToSize:maxContentSizeForText lineBreakMode:NSLineBreakByWordWrapping];
[label setFrame:CGRectMake(xPosition, yPosition, stringTextSize.width, stringTextSize.height);
[label setNumberOfLines:1000];

您的标签可能是xib文件或故事板中的属性,行数只是说您希望标签变得非常大,因为我们不能说“无限”我通常只使用1000指示最多1000行文本