UITableViewCell with dynamic height iOS

前端 未结 12 2354
日久生厌
日久生厌 2020-11-27 17:54

I have implemented TableView with CustomCell in my app,

I want dynamic height of my UITableViewCell according to text length in UITableViewCell

12条回答
  •  盖世英雄少女心
    2020-11-27 18:47

    Try This, It worked like a charm! for me,

    In viewDidLoad write this code,

    -(void)viewDidLoad 
    {
    [super viewDidLoad];
     self.tableView.estimatedRowHeight = 100.0; // for example. Set your average height
     self.tableView.rowHeight = UITableViewAutomaticDimension;
    }
    

    In cellForRowAtIndexPath write this code,

     -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
     {
      static NSString *CellIdentifier = @"Cell";
      UITableViewCell *cell = [tableView 
      dequeueReusableCellWithIdentifier:CellIdentifier];
     if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] ;
      }
        cell.textLabel.numberOfLines = 0; // Set label number of line to 0
        cell.textLabel.text=[[self.arForTable objectAtIndex:indexPath.row] valueForKey:@"menu"];
        [cell.textLabel sizeToFit]; //set size to fit 
        return cell;
     }
    

    Hopes so this will help for some one .

提交回复
热议问题