1

I have a UITableView that uses prototype cells. The cells have a custom class called dataCell. The custom cells also have three UILabels:idLabel, contLabel, and expLabel. The cells properly resize based on the amount of text in expLabel; however, I cannot get the label itself to resize. Some labels resize when I scroll down; however, they also revert to showing only two lines and omitting text when I scroll back up. Here is my code

- (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;  }

Any help would be much appreciated

4

1 回答 1

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 行文本最大值

于 2013-05-23T19:47:38.240 回答