2012-01-31 36 views
1

我想在UITableViewCell中显示自定义的UILabel,但是出了点问题。 我的代码:UITableViewCell addSubview和CGRectMake问题

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

结果的截图:enter image description here

回答

2

您确定您正在获取评论值,因为通过查看屏幕截图,就会看到您将垃圾设置为标签的文本。

此外,您必须设置标签的框架而不是其边界,因为您希望它的位置与UITableViewCell相关。

更改代码 titleLabel.bounds = CGRectMake(20,20,300,100); 至 titleLabel.frame = CGRectMake(20,20,300,100);

2

您应该设置titleLabel.frame没有titleLabel.bounds。界限与位置无关。