在启用了部分和分页的情况下面对UICollectionview大小调整问题。 目前,我希望每个部分显示7列和6行,并且单元格的大小固定,所以我创建如下。
var margin: CGFloat = 10
let cellsPerRow = 7
let numberOfRows = 6;
let cellHeight = 50
let size = UIScreen.main.bounds.size.width - CGFloat(cellsPerRow*cellHeight)
margin = size/CGFloat(cellsPerRow);
collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: 300), collectionViewLayout: UICollectionViewFlowLayout.init())
guard let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout else { return }
flowLayout.minimumInteritemSpacing = margin
flowLayout.minimumLineSpacing = 0
flowLayout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
flowLayout.scrollDirection = UICollectionViewScrollDirection.vertical
collectionView.register(MyCollectionViewCell.self, forCellWithReuseIdentifier: "collectionCell")
collectionView.isPagingEnabled = true;
collectionView.dataSource = self;
collectionView.delegate = self;
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 20;
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 42;
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//return collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier:"collectionCell", for: indexPath) as! MyCollectionViewCell
cell.backgroundColor = UIColor.random()
return cell;
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let marginsAndInsets = flowLayout.sectionInset.left + flowLayout.sectionInset.right + flowLayout.minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
return CGSize(width: itemWidth, height: itemWidth)
}
我想在屏幕上只显示集合视图的一个部分。最初,它工作正常但经过一些滚动(在第6至第7节之后)我面临着尺寸问题。它向我展示了上一节的一些部分。请参阅附带的问题截图。
请帮帮我。提前谢谢。
答案 0 :(得分:0)
对于复杂的分页,最好使用scrollView Delegate:
scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)
(见documentation
在您的代码中,它将如下所示:
func scrollViewWillEndDragging(_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let pageHeight : CGFloat = /* number of rows */ 6 * /* height of row */ 50 + /* number of interspacing */ 5 * /* interspacing */ 10
//This is where the scrollview Gonna stops
let naturalDestination = targetContentOffset.pointee.y
//Round it to the nearest page
let computedDestination = round(targetContentOffset.pointee.y / pageHeight) * pageHeight
//Edit the targetOffset
targetContentOffset.pointee.y = computedDestination
}