我试图在UITableViewCell中显示自定义UILabel,但有些地方出错了。我的代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *currentComment = [comments objectAtIndex:indexPath.row];
static NSString *CellIdentifier = @"TitleCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
int commentLevel = [[currentComment objectForKey:@"level"] intValue];
NSLog(@"Comment level: %i", commentLevel);
NSString *commentText = [currentComment objectForKey:@"text"];
UILabel *titleLabel = [[UILabel alloc] init];
titleLabel.numberOfLines = 0;
[titleLabel setFont:[UIFont fontWithName:@"Verdana" size:17.0]];
CGSize textSize;
if (commentLevel == 0) {
textSize = [commentText sizeWithFont:titleLabel.font constrainedToSize:CGSizeMake(310, FLT_MAX) lineBreakMode:UILineBreakModeWordWrap];
//titleLabel.bounds = CGRectMake(5, 5, textSize.width, textSize.height);
} else {
textSize = [commentText sizeWithFont:titleLabel.font constrainedToSize:CGSizeMake((295-10*commentLevel), FLT_MAX) lineBreakMode:UILineBreakModeWordWrap];
//titleLabel.bounds = CGRectMake(15, 5, textSize.width, textSize.height);
}
titleLabel.bounds = CGRectMake(20, 20, 300, 100);
titleLabel.text = commentText;
[cell.contentView addSubview:titleLabel];
return cell;
}结果截图:

发布于 2012-01-31 23:28:50
您确定您正在获得注释值,因为通过查看屏幕截图,它看起来就像您正在将垃圾设置为标签的文本。
此外,您必须设置标签的框架,而不是它的边界,因为您希望它的位置与UITableViewCell相关。
将代码titleLabel.bounds = CGRectMake(20,20,300,100);改为titleLabel.frame = CGRectMake(20,20,300,100);
发布于 2012-01-31 23:24:38
您应该设置titleLabel.frame而不是titleLabel.bounds。边界与位置无关。
https://stackoverflow.com/questions/9082030
复制相似问题