无法在tableView:cellForRowAtIndexPath:方法中设置标签框架

时间:2014-02-20 13:38:25

标签: ios uitableview ios7 uilabel

tableViewCell方法中的标签框架无法在ableView:cellForRowAtIndexPath:方法中设置。事实上,如NSLog中所示,标签的框架已更改,但未在视图中显示。 我预计标签(带绿色背景)应该高于图片中的标签,可以显示其中的所有文字。在Prototype Cell中创建了Identifier storyboard“单元格”。任何帮助将不胜感激。

ps:Xcode 5.0.2,iOS7

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString * str = @"Do any additional setup after loading the view, typically from a nib Do any additional setup after loading the view, typically from a nib Do any additional setup after loading the view, typically from a nib";
    NSArray *array = [NSArray arrayWithObjects:str, str, str , str, str, str, nil];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row;
    CGSize sizeConstraint = CGSizeMake(tableView.frame.size.width, 2000);
    CGSize size = [[array objectAtIndex:row] boundingRectWithSize:sizeConstraint options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont fontWithName:FontName size:FontSize]} context:nil].size;

    return size.height + 20;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row;
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    UILabel *label = (UILabel *)[cell.contentView viewWithTag:1];
    label.autoresizingMask = UIViewAutoresizingNone;
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.font = [UIFont fontWithName:FontName size:FontSize];
    label.backgroundColor = [UIColor greenColor];
    label.text = [array objectAtIndex:row];

    CGSize sizeConstraint = CGSizeMake(tableView.frame.size.width, 2000);
    CGSize size = [label.text boundingRectWithSize:sizeConstraint options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: label.font} context:nil].size;
    CGRect rect = label.frame;
    rect.size.height = size.height;
    [label setFrame:rect];
    NSLog(@"label height :%f", label.frame.size.height);
    [label sizeThatFits:sizeConstraint];
    return cell;
}

enter image description here enter image description here

滚动tableView时,您可以看到第一个和第二个单元格中的标签现在已经很好地显示了。 (这里我只是滚动出两个单元格并将它们拉回来。)

after scroll the tableView

2 个答案:

答案 0 :(得分:1)

在你的帖子中,我没有找到用于设置标签框架的labelBible的定义。

使用约束它很快:

enter image description here

enter image description here

通过这种方式,您无需在-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法中执行任何操作。

编辑:使用约束:必须检查Use Autolayout

enter image description here

希望能够按你的意愿工作。

答案 1 :(得分:0)

从标签框的文件检查器中取消选中自动布局。