我已经创建了一个UIViewController的可表示视图,我正在尝试将单元格垂直居中在collectionview中。
但是,单元格显示的位置略低于UICollectionview的中心。
我相信问题是,尽管有可见的带有高度的单元格,collectionView.contentSize.height为0。 (我已经注释了对应的行,它是从底部开始的6行)
为什么它会返回零?
struct MyCollectionView : UIViewRepresentable {
@Binding var data:[WordPairCollectionStruct]
var didSelectItem: ((_ indexPath: IndexPath)->()) = {_ in }
func makeUIView(context: Context) -> UICollectionView {
let layout = UICollectionViewFlowLayout()
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.register(UINib(nibName: "WordPairCell", bundle: nil), forCellWithReuseIdentifier: "myCell")
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.dataSource = context.coordinator
collectionView.delegate = context.coordinator
collectionView.backgroundColor = .blue
collectionView.alwaysBounceVertical = true
return collectionView
}
func updateUIView(_ uiView: UICollectionView, context: Context) {
// uiView.reloadData()
}
func makeCoordinator() -> Coordinator {
return Coordinator(data: data)
}
class Coordinator: NSObject, UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
var data: [WordPairCollectionStruct]
init(data: [WordPairCollectionStruct]) {
self.data = data
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: WordPairCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! WordPairCell
cell.wordText.text = data[indexPath.row].word
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Tapped \(indexPath.row)")
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let numberOfItems = CGFloat(collectionView.numberOfItems(inSection: section))
let combinedItemWidth = (numberOfItems * flowLayout.itemSize.width) + ((numberOfItems - 1) * flowLayout.minimumInteritemSpacing)
let padding = (collectionView.frame.width - combinedItemWidth) / 2
print("** \(collectionView.contentSize.height)")
// Line of interest **********
let top = max((collectionView.frame.height - collectionView.contentSize.height) / 2, 0)
return UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0)
}
}
}