【问题标题】:UITableView not scrollable but enough heightUITableView 不可滚动但足够高
【发布时间】:2016-06-27 01:36:07
【问题描述】:

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

PS:对于动态单元格高度,我使用了这个:

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

简而言之:我希望表格视图的行为类似于高度变量列表。

【问题讨论】:

    标签: ios swift xcode autolayout


    【解决方案1】:

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

    所以你要做的是,首先让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()
    }
    

    就是这样,如果您正确设置了滚动视图的约束,那么它肯定会按您的预期工作......

    更新

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

    可滚动的表格视图:

    可滚动的滚动视图:

    【讨论】:

    • 谢谢,但我不起作用,因为 contentSize.height 返回行数 *estimatedRowHeight,但我的行高是可变的。想法?
    • 不,contentSize 不返回estimatedRowHeight,它返回tableView 显示所有单元格所需的高度。我创建了具有动态高度单元的演示,它按预期工作。查看更新的答案。
    • 在使用 XCode 11 的 iOS 13 上,contentSize 不会在不强制布局循环的情况下立即更新。在 iOS 13 之前,tableview.contentsize.height 返回正确的高度。但是对于 iOS 13,您必须调用 layoutIfNeeded 才能获得正确的 contentSize。我仍在寻找可以澄清 UITableview 上是否有任何布局周期更改的参考资料,但到目前为止我找不到任何内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 2021-06-03
    • 2019-11-07
    • 1970-01-01
    • 2015-02-12
    • 2012-11-23
    相关资源
    最近更新 更多