我正在制作一个具有购物车的Swift应用程序,并希望使用uicollectionview来显示购物车项目。我希望uicollectionview显示没有滚动条的购物车项目。如果没有商品,我想用一个标签说明购物车中没有商品的uicollectionview替换。我知道如何添加具有固定高度的uicollectionview,只是不具有动态高度。我没有使用情节提要,而是为所有布局使用了锚点。预先感谢!
import UIKit
import SnapKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
var collection: UICollectionView?
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 100, height: 200)
collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
collection?.delegate = self
collection?.dataSource = self
collection?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
view.addSubview(collection!)
collection?.snp.makeConstraints { (make) in
make.left.top.right.equalToSuperview()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
collection?.snp.remakeConstraints({ (make) in
make.left.top.right.equalToSuperview()
make.height.equalTo(collection!.collectionViewLayout.collectionViewContentSize.height)
})
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
return cell
}
}
func load() {
myCellDataSource = [Some Data]
collectionView.reloadData()
//Here you will update the height Constraint.
DispatchQueue.main.async {
let height = collectionView.contentSize.height
collectionView.constraints.forEach { (constraint) in
if constraint.firstAttribute == .height {
constraint.constant = height
}
}
}
}
注意: collectionView的原始大小可以为0或屏幕的整个高度,具体取决于您要实现的目标。 (此外,您需要执行此操作的其他约束不能同时干扰collectionView的高度,例如:顶部和底部。)