如何基于uitableview动态增加scrollview的高度

PPS*_*ein 3 iphone objective-c uitableview uiscrollview ios

目前,我已经开发了UIScrollView、UITableView、另外 3 个 UIView 输入和 UIButton 最后的项目。在该页面中,UIScrollView 的高度将根据 UITableView 的高度动态增加。

对于 UITableView 没有更多的滚动。它的高度也将根据Async 加载的JSON 数据添加的行数来增加,如下所示。

productHeight = 44;
productHeight *= _nsOrderItems.count;
productHeight = productHeight + 100;

if (isHeaderTap) {
    self.productTableHeight.constant = 50;
} else {
    self.productTableHeight.constant = productHeight;
}

//then the tableView must be redrawn
[self.productTable setNeedsDisplay];
Run Code Online (Sandbox Code Playgroud)

我的问题是我想根据 UITableView 的高度增加 UIScrollView 的高度。

- (void)viewDidLayoutSubviews {
    [self.scrollView setContentSize:CGSizeMake(_scrollView.frame.size.width, _btnEdit.frame.origin.y + _btnEdit.frame.size.height)];
}
Run Code Online (Sandbox Code Playgroud)

Shr*_*ade 6

你绝对可以做到,

  1. 首先确保单元格子视图的约束必须设置为从上到下,以便计算单元格所需的高度。

  2. 确保您的委派设置如下

    -(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
      return 44;
     } 
    
     -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
     }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 设置 tableView 的高度约束并制作该约束的出口。

  4. 将以下方法添加到您要动态调整 tableView 大小的类中。

    - (void)adjustHeightOfTableview
    {
        CGFloat height = self.tableView.contentSize.height;
        //CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;
    
       /* 
        Here you have to take care of two things, if there is only    tableView on the screen then you have to see is your tableView going below screen using maxHeight and your screen height,
     Or you can add your tableView inside scrollView so that your tableView can increase its height as much it requires based on the number of cell (with different height based on content) it has to display.
       */
    
       // now set the height constraint accordingly
        self.constraintHeightTableView.constant = height;
    
       //If you want to increase tableView height with animation you can do that as below.
    
        [UIView animateWithDuration:0.5 animations:^{
        [self.view layoutIfNeeded];
        }];
    }
    
    Run Code Online (Sandbox Code Playgroud)
  5. 当您准备好表的数据源时调用此方法,并将该方法调用为

    dispatch_async(dispatch_get_main_queue(), ^{
    
       [self.tableView reloadData];
    
       //In my case i had to call this method after some delay, because (i think) it will allow tableView to reload completely and then calculate the height required for itself. (This might be a workaround, but it worked for me)
       [self performSelector:@selector(adjustHeightOfTableview) withObject:nil afterDelay:0.3];
    });
    
    Run Code Online (Sandbox Code Playgroud)