【发布时间】:2018-08-29 23:34:26
【问题描述】:
我有一个带有自定义单元格的 collectionView。我想在我的单元格中使用特定的布局来布局 imageView,但它的布局不正确。
第 1 行和第 3 行布局正确,但第 2 行布局不正确。正确的布局应该是中间的每张图片都应该低于两端的其他两张。
问题在 CollectionViewCell 内部,我使用模数将每个奇数单元格设置为低于每个偶数单元格,但由于第二行(或每个奇数行)中间单元格的模数将始终是偶数布局布局正确,但没有给我想要的。
我怎样才能让布局看起来像下图?
代码:
override func viewDidLoad() {
super.viewDidLoad()
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsetsMake(15, 0, 5, 0)
layout.scrollDirection = .vertical
collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
// collectionView datasource, delegate, and cell registration set
view.addSubview(collectionView)
collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
collectionView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 5).isActive = true
collectionView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -5).isActive = true
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 9
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CustomCell
cell.item = indexPath.item
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (view.frame.width - 25) / 3
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 25
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
这是我用来设置布局的 CollectionViewCell 中的代码:
class CustomCell: UICollectionViewCell {
var item: Int = 0 {
didSet {
setLayout()
}
}
func setLayout() {
addSubview(imageView)
imageView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
imageView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
if item % 2 == 0 {
imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: -10).isActive = true
imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -10).isActive = true
} else {
imageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true
imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 10).isActive = true
}
}
}
【问题讨论】:
标签: ios swift uicollectionview uicollectionviewcell modulus