ios – 调整容器视图的高度以匹配嵌入式UITableView

使用Storyboards和Autolayout,我有一个带有UIScrollView的UIViewController作为主视图.我在滚动视图中嵌入了几个容器视图.其中一些嵌入式容器视图包含UITableViews,每个视图都具有不同高度的单元格.我需要tableView的高度足够大,以便一次显示所有单元格,因为在tableView上将禁用滚动.

在主UIViewController中,必须定义容器视图的高度,以使滚动视图正常工作.这是有问题的,因为一旦所有不同高度的单元格完成渲染,我无法知道我的tableView有多大.如何在运行时调整容器视图的高度以适应我的非滚动UITableView?

到目前为止,我已经完成了以下工作:

// in embedded UITableViewController
// 
- (void)viewDidLoad {
  // force layout early so I can determine my table's height
  [self.tableView layoutIfNeeded];

  if (self.detailsDelegate) {
        [self.detailsTableDelegate didDetermineHeightForDetailsTableView:self.tableView];
  }
}

// in my main UIViewController
// I have an IBOutlet to a height constraint set up on my container view
// this initial height constraint is just temporary,and will be overridden
// once this delegate method is called
- (void)didDetermineHeightForDetailsTableView:(UITableView *)tableView
{
  self.detailsContainerHeightConstraint.constant = tableView.contentSize.height;
}

这工作正常,我对结果很满意.但是,我有一两个容器视图要添加,它们将具有非滚动的tableViews,我不想为每个容器视图创建一个新的委托协议.我认为我不能制定我具有通用性的协议.

有任何想法吗?

解决方法

这是我最终做的事情:
// In my embedded UITableViewController:
- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 60.0;

    // via storyboards,this viewController has been embeded in a containerView,which is
    // in a scrollView,which demands a height constraint. some rows from our static tableView
    // might not display (for lack of data),so we need to send our table's height. we'll force
    // layout early so we can get our size,and then pass it up to our delegate so it can set
    // the containerView's heightConstraint.
    [self.tableView layoutIfNeeded];

    self.sizeforEmbeddingInContainerView = self.tableView.contentSize;
}

// in another embedded view controller:    
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    self.sizeforEmbeddingInContainerView = self.tableView.contentSize;
}

// then,in the parent view controller,I do this:
// 1) ensure each container view in the storyboard has an outlet to a height constraint
// 2) add this:
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    self.placeDetailsContainerHeightConstraint.constant = self.placeDetailsTableViewController.sizeforEmbeddingInContainerView.height;
    self.secondaryExperiencesContainerHeightConstraint.constant = self.secondaryExperiencesViewController.sizeforEmbeddingInContainerView.height;
}

我还没有这样做,但最好创建一个具有CGSize sizeforEmbeddingInContainerView属性的协议,每个子视图控制器都可以采用.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...