【发布时间】:2021-09-15 09:39:51
【问题描述】:
我有一个带有绿色背景的水平 UICollectionView(附加图像),我想根据可用单元格的数量调整它的宽度。之后,按钮需要附加到集合视图尾随锚点
例如:我在集合视图中有一张照片,它的视图宽度为 100。用户按下按钮,将照片添加到集合中,宽度增加到 200。因此 addImageButton 已向右移动。
它应该看起来像这样:
我当前的代码是这样的:
class ImagesViewController: UIViewController {
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 8
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.register(ImagesCollectionViewCell.self, forCellWithReuseIdentifier: ImagesCollectionViewCell.reuseIdentifier)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.translatesAutoresizingMaskIntoConstraints = false
return collectionView
}()
lazy var addImageButton: UIButton = {
let btn = UIButton()
btn.layer.cornerRadius = 8
btn.clipsToBounds = true
btn.contentMode = .scaleAspectFill
btn.backgroundColor = Colors.tintDefault
btn.setImage(UIImage(named: "addImage"), for: .normal)
btn.translatesAutoresizingMaskIntoConstraints = false
btn.addTarget(self, action: #selector(handleAddImage), for: .touchUpInside)
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Colors.backgroundPrimary
[collectionView, addImageButton].forEach { view.addSubview ($0) }
collectionView.anchor(top: top.bottomAnchor, leading: view.leadingAnchor, paddingTop: 20, width: 272, height: 80)
collectionView.backgroundColor = .green
addImageButton.centerYAnchor.constraint(equalTo: collectionView.centerYAnchor).isActive = true
addImageButton.anchor(leading: collectionView.trailingAnchor, paddingLeft: 32, width: 24, height: 24)
}
}
extension ImagesViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
// Some code here... (numberOfItemsInSection, cellForItemAt, etc)
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 80, height: 80)
}
}
请仔细阅读问题!
需要动态 collectionView 宽度,而不是单元格宽度!
请帮我设置集合视图的动态宽度
【问题讨论】:
-
只需将该 + 图标作为一个新单元格,不要使用集合视图的宽度。而已。此外,如果您将 + 作为集合视图的第一行,则对 UX 有好处。
-
那里可以放 4-5 或 10 张图片吗?如果图像的数量不能适应当前的宽度怎么办?它是水平滚动还是垂直显示在下一行?
-
@FahimParkar 非常感谢您的建议。我也一直在考虑这个选项(或添加 + 图标作为集合视图页脚)。但在这种情况下,我将不得不使用闭包或委托来打开图像选择器
-
@TarunTyagi 不,照片的最大数量是 3。所以它只有一排照片和旁边的 + 按钮
-
@Russ:好的,问题出在哪里?与单击按钮相同。这样,即使您有 3 行以上,它也很容易。无论如何,选择是你的。
标签: ios swift uicollectionview autolayout nslayoutconstraint