根据单元格Objective-C中的标签文本(动态)增加“单元格高度”

时间:2017-03-23 06:39:34

标签: ios objective-c iphone xcode custom-cell

如何根据单元格中的标签文本(动态)增加单元格高度。在下面的代码中,lblAnswer获取动态数据,基于此,单元格高度应该增加。尝试下面的代码,但不适合我。 TIA

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    EmpViewCell *cell = (EmpViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {


        cell = [[EmpViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

        cell.lblAnswer.lineBreakMode = NSLineBreakByWordWrapping;
        cell.lblAnswer.numberOfLines = 0;
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];

        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"EmpViewCell" owner:self options:nil];

        for (id currentObject in topLevelObjects){
            if ([currentObject isKindOfClass:[UITableViewCell class]]){
                cell =  (EmpViewCell *) currentObject;
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
            }
        }
    }
    NSMutableDictionary* emmpdict = [_emparr objectAtIndex:indexPath.row];

    cell.lblEmpName.text = [NSString stringWithFormat:@"%@",[emmpdict objectForKey:@"EmployeeName"]];

    cell.lblQuestion.text=[NSString stringWithFormat:@"%@",[emmpdict objectForKey:@"Question"]];

    cell.lblAnswer.text=[NSString stringWithFormat:@"%@",[emmpdict objectForKey:@"Answer"]];

    return cell;

}

3 个答案:

答案 0 :(得分:0)

您可以使用UITableViewAutomaticDimension轻松实现此目的。

只需使用以下鳕鱼 e:

your_tableView.estimatedRowHeight = 100; //或任何temorary值,因为它将在获得动态高度后被替换

your_tableView.rowHeight = UITableViewAutomaticDimension;

注意:要正常使用,请确保正确应用tableViewCell中的所有约束

答案 1 :(得分:0)

如果您已将故事板中的UILabel添加到UITableviewCell,则不会将单元格设为nil。然后你的一些代码不会执行,即if(cell == nil)因为cell不是nil。

在Storyboard中执行此更改: 确保已将UILabel的顶部,底部,前导和尾部约束赋予UITableViewCell contentView。

  1. 然后将UILabel的行数设置为' 0'也可以换行" Word Wrap"。
  2. enter image description here

    1. 在UITableViewDelegate的Controller中 heightForRow 方法:

      - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
          {
              tableView.estimatedRowHeight = 100;
              return UITableViewAutomaticDimension;
          }
      
    2. 这将有助于解决上述要求。

答案 2 :(得分:0)

对于新的iOS 8,有一种新方法可以实现这一点。

目标c:

 - (void)viewWillAppear:(BOOL)animated {
      [super viewWillAppear:animated];
      self.tableView.estimatedRowHeight = 40.0; // for example. Set your average height 
      self.tableView.rowHeight = UITableViewAutomaticDimension;
      [self.tableView reloadData];
    }

swift 3.0:

override func viewWillAppear(animated: Bool) {
    self.tableView.estimatedRowHeight = 40 // for example. Set your average height 
    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.reloadData()

}