swift - 如何让scrollview在swift中分别滚动到它的内容高度
问题描述
我在情节提要中有如下视图层次结构
这里是内容的主要限制top = 0, leading = 0, trailing = 0, bottom = 0
这里是滚动视图约束top = 0, leading = 0, trailing = 0, bottom = 0
在这里查看约束top = 0, leading = 0, trailing = 0, bottom = 0
对于ContentView约束top = 0, leading = 0, trailing = 0
对于TblReview约束top = 0, leading = 0, trailing = 0, bottom = 20
对于Productcollectionview约束top = 0, leading = 0, trailing = 0, bottom = 20, height = 400
我在 swift 文件中有 Productcollectionview 高度出口,如下所示
而且我不希望collectionview单独滚动..我希望总视图根据collectionview单元格滚动..所以我写了下面的代码但是使用这段代码contentView and tblReview also scrolling upto productioncollectionview height
我需要contentView应该滚动到它的内容高度并且tblReview应该滚动到它的行
如何分别滚动到它的高度。
请帮我解决这个问题
@IBOutlet weak var productCollHeight: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
productCollectionView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let collectionView = object as? UICollectionView
if collectionView == self.productCollectionView{
if(keyPath == "contentSize"){
if let newvalue = change?[.newKey]
{
let newsize = newvalue as! CGSize
self.productCollHeight.constant = newsize.height
}
}
}
}
@IBAction func aboutCompany(_ sender: UIButton){
self.productCollectionView.isHidden = true
self.tblReview.isHidden = true
self.contentView.isHidden = false
}
@IBAction func review(_ sender: UIButton){
self.productCollectionView.isHidden = true
self.tblReview.isHidden = false
self.contentView.isHidden = true
}
@IBAction func productOfSeller(_ sender: UIButton){
self.productCollectionView.isHidden = false
self.tblReview.isHidden = true
self.contentView.isHidden = true
}
我根据需要隐藏和显示 tblReview 和 contentView
使用上面的代码 tblReview 和 contentView 也滚动到 productCollectionView 高度..请帮我解决这个错误
编辑:没有滚动share this seller
视图,所以这里的contentView 高度不是那么长,但是如果我滚动 contentView 也滚动太长,就像 productioncollectionview
解决方案
如果您的所有约束都是正确的,而不仅仅是像这样使用它,您就不需要每次都计算。UICollectionView
有intrinsicContentSize
它会正确计算它。
final class ContentSizedCollectionView: UICollectionView {
override var contentSize:CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
layoutIfNeeded()
return CGSize(width: UIView.noIntrinsicMetric, height: contentSize.height)
}
}
将该代码放在控制器中或您想要放置的任何位置并将ContentSizedCollectionView
类分配给您的collectionview。
注意:您也可以UITableView
在创建 for 之后使用它UITableView
。
推荐阅读
- sql - 使用数据类型“几何”时使用 mariadb/phpmyadmin 时会发生什么
- permissions - ECS 任务访问启用阻止公共访问的 S3 存储桶网站:“访问被拒绝”
- ios - xCode 项目未在 macOS Catalina 10.15.5 上找到 c++ 标准库
- object - 如何切割 3D 对象的一部分?
- python - Flask SQLAlchemy:按 id 获取记录
- mysql - 续集错误:包括意外。元素必须是模型、关联或对象
- node.js - 我们可以使用客户端 IP 地址在 node.js 上发出 http 请求吗?
- angular - Dotnet 核心 3.1 返回 401 和状态文本 OK
- python - Python / Matplotlib:带有contourf的颜色条不尊重自定义cmap的刻度标签
- javascript - 跨度标签内的可编辑文本并将光标放在末尾(Javascript)