2012-01-31 124 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。界限與位置無關。