UITableView不可滚动但有足够的高度

时间:2016-06-27 01:36:08

标签: ios swift xcode autolayout

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

PS:对于动态细胞高度,我使用了这个:

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

很简单:我希望表视图的行为类似于高度变量列表。

1 个答案:

答案 0 :(得分:3)

还有其他方法可以做到这一点,但就我而言,我已经做到了,

所以你需要做的是,首先让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,但是你需要滚动查看。

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的约束,那么它肯定会像你期望的那样工作......

<强>更新

我创建了一个包含动态单元格的演示,请参阅下面的输出

Scrollable TableView:

enter image description here

Scrollable ScrollView:

enter image description here