UICollectionView项目按其部分位置进行偏移

时间:2018-04-09 19:54:02

标签: ios swift uicollectionview

我已将UICollectionView用于呈现WKWebview作为contentView的UICollectionViewCell子视图,并将UIPageControl绑定到它。

  

注意:为了在渲染时演示问题,我将单元格宽度的大小设为100

问题首先是Webview(这是集合视图第一部分中的一个单元格)按预期显示,但第二个单元格显示的是单元格宽度偏移。

UICollectionViewDelegate覆盖方法

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1;
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // set this width for just showing screenshot for this question 
    return CGSize(100, height: view.frame.height-view.safeAreaInsets.top);
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0;
}

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    self.webviewsPageControl.currentPage = indexPath.section;
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    self.webviewsPageControl.numberOfPages = self.webviews?.count ?? 0;
    return self.webviews?.count ?? 0;
}

15

为了识别,我将UICollectionViewCell背景设为红色。

所以问题是,如何删除偏移量以便webview可以并排呈现。为什么会出现这种情况。

提前致谢。

2 个答案:

答案 0 :(得分:0)

您需要在流布局上设置minimumLineSpacing = 0,例如

let layout = UICollectionViewFlowLayout();
layout.minimumLineSpacing = 0
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)

答案 1 :(得分:0)

我使用以下代码来减少列之间的间距:

let cellsPerRow = 2 //number of columns or number of cells in each row

在viewDidLoad()中:

guard let flowLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout else { return }
        flowLayout.minimumInteritemSpacing = 0 //setting margin between cell columns = 0
        flowLayout.minimumLineSpacing = 0// setting margin between cell lines = 0
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) //Not required, solutions works without it as well

最后,

//function to set number of columns
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)
    }