【发布时间】:2020-10-06 14:48:42
【问题描述】:
此 collectionView 的行不能有 3 个单元格。
- 通过情节提要添加了 UICollectionView,单元格相同,然后添加了约束。所有其他东西都是通过代码制作的。
- 如果我让单元格为空,我会让它们完全正方形,但在 iPhone 11 上它们是 6 行
- 如果添加一些网点,如 IE 一个图像和一个标签在堆栈中(固定 0,0,00 fil,fill),它们分布不均
- 如果我通过单元格中的代码对图像进行约束,会发生一些变化,但结果绝不是我所期望的,每行 3 个单元格。
- 两种方法都失败了
我的控制器
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myCollectionView: UICollectionView!
var collectionData = ["1????", "2????", "3 ????", "4????", "5????", "6????", "7????", "8????", "9????", "10????", "11????", "12????"]
override func viewDidLoad() {
super.viewDidLoad()
myCollectionView.delegate = self
myCollectionView.dataSource = self
configureCollectionView()
}
private func configureCollectionView() {
let widthOfScreen = (view.frame.size.width - 20) / 3
let layout = myCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: widthOfScreen , height: widthOfScreen )
layout.sectionInset = UIEdgeInsets(top: 40.0,
left: 10.0,
bottom: 40.0,
right: 10.0)
}
private func configureCollectionView2() {
let width = view.bounds.width
let padding: CGFloat = 12
let minimumItemSpacing: CGFloat = 10
let availableWidth = width - (padding * 2) - (minimumItemSpacing * 2)
let itemWidth = availableWidth / 3
let layout = myCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsets(top: padding,
left: padding,
bottom: padding,
right: padding)
layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
}
}
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(self.collectionData[indexPath.item])
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collectionData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let model = collectionData[indexPath.item]
let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: MyCollectionViewCell.reuseId, for: indexPath) as! MyCollectionViewCell
cell.configure(with: model)
return cell
}
}
我的手机
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
static let reuseId = "MyCollectionViewCell"
// @IBOutlet weak var myCellImage: UIImageView!
// @IBOutlet weak var myCellLabel: UILabel!
func configure(with: String) {
backgroundColor = .systemPink
// myCellImage.backgroundColor = .black
// myCellImage.translatesAutoresizingMaskIntoConstraints = false
//
// NSLayoutConstraint.activate([
//
// myCellImage.widthAnchor.constraint(equalToConstant: 50),
// myCellImage.heightAnchor.constraint(equalToConstant: 50),
//
// ])
}
}
【问题讨论】:
标签: swift uicollectionview uicollectionviewlayout