对UITableViewCells和动态高度使用autolayout

时间:2014-09-25 16:32:13

标签: ios objective-c uitableview autolayout

所以我查看了this answer。但是我仍然无法正确返回iOS7的高度。我有一个表格视图,其中我在自动布局中布置了一个相当复杂的单元格。每当我尝试覆盖heightForRowAtIndex(使其与iOS7兼容)时,我得到的排高度似乎无法正确计算。当我不覆盖heightForRowAtIndex时,一切都很有效,除了它不适用于iOS7。我也试图使用xib自动布局整个事物。我的DipticCell.m中没有任何逻辑。它全部在UITableView子类中。

-(id)init{
    //Implementation details go BELOW
    self.dataSource = self;
    self.delegate = self;
    [self registerNib:[UINib nibWithNibName:@"DipticCell" bundle:nil] forCellReuseIdentifier:@"dipticCell"];
    [self registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell2"];
    self.rowHeight = UITableViewAutomaticDimension;
    offScreenCells = [[NSMutableDictionary alloc] init];
    return self;

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *reuseIdentifier = @"dipticCell";
    if (indexPath.row > 0){
        reuseIdentifier = @"cell2";
    }

    UITableViewCell *cell = [offScreenCells objectForKey:reuseIdentifier];
    if (!cell) {
        cell = [self dequeueReusableCellWithIdentifier:reuseIdentifier];
        [offScreenCells setObject:cell forKey:reuseIdentifier];
    }


    [cell setNeedsUpdateConstraints];
    [cell updateConstraintsIfNeeded];


    cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds));


    [cell setNeedsLayout];
    [cell layoutIfNeeded];

    CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    height += 1.0f;
    return height;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0){
        DipticCell *cell = [tableView dequeueReusableCellWithIdentifier:@"dipticCell"];
        if (cell == nil) {
            cell = [[DipticCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"dipticCell"];
        }
        return cell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell2"];
        }
        cell.textLabel.text = @"one";
        return cell;
    }

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 10;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

只是为了确认所有内容都在contentView中。

enter image description here

此外,当我覆盖heightForRowAtIndexPath时,我得到一个&#34;无法同时满足约束。&#34;警告。但是,当我不能覆盖它时,事情似乎有效(这是有道理的,因为单元格应该只适应内容的高度,现在我试图以高度1覆盖它。)< / p>

如果您想运行该项目,可以使用以下链接。 AutoLayoutCells

1 个答案:

答案 0 :(得分:0)

大部分时间对我有用的是确保您有从单元格顶部到单元格底部的约束路径。

因此,如果您的单元格为三个标签:label1,label2,label3和all将显示在彼此之下。比添加约束:

cell.top to label1.top
label1.bottom to label2.top
label2.bottom to label3.top
label3.bottom to cell.bottom

通过约束来定义单元格的高度。因此,请确保连接所有定义单元格高度的子视图。