首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UITableViewCell addSubview和CGRectMake问题

UITableViewCell addSubview和CGRectMake问题
EN

Stack Overflow用户
提问于 2012-01-31 23:20:51
回答 2查看 1.3K关注 0票数 1

我试图在UITableViewCell中显示自定义UILabel,但有些地方出错了。我的代码:

代码语言:javascript
复制
- (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;
}

结果截图:

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-01-31 23:28:50

您确定您正在获得注释值,因为通过查看屏幕截图,它看起来就像您正在将垃圾设置为标签的文本。

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

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

票数 2
EN

Stack Overflow用户

发布于 2012-01-31 23:24:38

您应该设置titleLabel.frame而不是titleLabel.bounds。边界与位置无关。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9082030

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档