UITableView不滚动,但足够的高度

我正在构build一个Storyboard,其中包含一个包含Table View的Scroll View。 我做的第一件事是禁用滚动的表视图,否则我们会得到两个嵌套的滚动条,erk! 但是,这是我的问题,我希望桌面视图的高度等于其单元格高度的总和。 (单元格高度是各种各样的,因为它们显示注释)。

PS:对于dynamic细胞高度,我用这个:

self.commentsTableView.estimatedRowHeight = 90.0 self.commentsTableView.rowHeight = UITableViewAutomaticDimension 

简而言之:我想要一个表视图行为像一个高度variables列表。

还有其他方法可以做到这一点,但在我的情况下,我已经做到了这一点,

所以你要做的是,首先让tableView的所有单元格加载,这样你可以检查是所有的tableView单元格加载如下,

 func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { //Update tableView Offset if indexPath.row() == (tableView.indexPathsForVisibleRows.last! as! NSIndexPath).row { //End of loading all Visible cells self.updateTableViewOffsetForTableView(self.tableView, withHeightConstraint: self.heightConstraintTableView) //If cell's are more than 10 or so that it could not fit on the tableView's visible area then you have to go for other way to check for last cell loaded } } 

然后在这之后,你必须得到你的tableView所需的高度,并将此高度设置为tableView的高度约束,以将tableView的高度增加到可见的所有单元格而不需要滚动tableView,但是您需要scrollView。

 func updateTableViewOffsetForTableView(tableView: UITableView, withHeightConstraint heightConstraintToBeUpdated: NSLayoutConstraint) { var heightRequiredForTable: CGFloat = tableView.contentSize.height //Set some random height first, it is easy for tableView to shrink its height to high to low. heightConstraintToBeUpdated.constant = 300 self.view!.layoutIfNeeded() self.view!.setNeedsUpdateConstraints() //Update the height constraint with height required for tableView heightRequiredForTable = tableView.contentSize.height heightConstraintToBeUpdated.constant = heightRequiredForTable self.view!.layoutIfNeeded() self.view!.setNeedsUpdateConstraints() } 

就是这样,如果你已经设置了正确的scrollView的约束,那么它肯定会像你期待的那样工作…

更新

我创build了一个具有dynamic单元格的演示,请参阅下面的输出,

可滚动的TableView:

在这里输入图像说明

可滚动滚动查看:

在这里输入图像说明