UITableView 高度等于 contentSize 高度 [英] UITableView height equal to contentSize height

查看:49
本文介绍了UITableView 高度等于 contentSize 高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个滚动视图,里面有一对标签和一个 tableView.我希望 tableView 由外部 scrollView 滚动,而不是 tableView 的 scrollView,所以我所做的是将 tableView 高度的约束设置为等于 contentSize 高度.但是我有这个问题,只有当推送动画完成时它的大小才正确(并且 viewDidLayoutSubviews 被调用,我猜)

I have a scroll view and inside of if couple labels and a tableView. I would like for that tableView to be scrolled by a outer scrollView and not the tableView's scrollView, so what I did is to set constraint for tableView height to be equal to contentSize height. But I have this problem that it is sized correctly only when push animation is completed (and viewDidLayoutSubviews gets called, I guess)

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    tableHeightConstraint?.constant = tableViewController.tableView.contentSize.height
}

视频链接

推荐答案

内容大小将随着滚动视图逻辑而刷新.所以布局子视图肯定是不够的.我有一种情况,根据内容调整表格视图的大小.我所做的是使用内在大小(它是故事板中的压缩优先级).我将表视图子类化并覆盖这些:

Content size will refresh with scroll view logic. So layout subviews is surely not enough. I have one case where I resize table view depending on it's content. What I do is use intrinsic size (it is that compression priority thing in storyboard). I subclass the table view and override these:

override var contentSize:CGSize {
    didSet {
        self.invalidateIntrinsicContentSize()
    }
}

override var intrinsicContentSize: CGSize {
    self.layoutIfNeeded()
    return CGSize(width: UIViewNoIntrinsicMetric, height: contentSize.height)
}

其余的可以通过约束来完成.在我的情况下,我不会进一步调整它的大小,然后它是超级视图,但是您必须做您必须做的事情.这里还有一点要小心:如果这不受限制,您会破坏表视图出列功能,并且可能会立即加载所有单元格,这可能会消耗大量内存和 CPU.如果可能的话,我会避免这种情况.如果没有,下一个最好的方法是在滚动视图上使用垂直堆栈视图,这应该会产生与您预期相同的结果.

The rest may then be done with constraints. Im my case I do not resize it further then it's superview but you do what you must. Still a bit of caution here: If this is not restricted you destroy the table view dequeuing feature and all the cells may be loaded instantly which may consume loads of memory and CPU. I would avoid that if possible. And if not, the next best thing is using a vertical stack view on a scroll view which should produce the same result you seem to expect.

这篇关于UITableView 高度等于 contentSize 高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆