1

CellのレイアウトをlineSpace=0,width=50 にしているのに2pxづつ各セルのx座標がずれてしまうのですが、理由が全く検討つきません。もし心あたりあれば教えていただけると助かります。

Collectionview生成側

    let backgroundView = UICollectionView(frame: view.frame, collectionViewLayout: UICollectionViewFlowLayout())
    backgroundView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: UICollectionViewCell.identifer)
    backgroundView.dataSource = backgroundLayout
    backgroundView.delegate = backgroundLayout
    backgroundView.isUserInteractionEnabled = false
    backgroundView.backgroundColor = UIColor.groupTableViewBackground

レイアウト側

class BackgroundLayout: NSObject ,UICollectionViewDelegateFlowLayout, UICollectionViewDataSource{

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: UICollectionViewCell.identifer, for: indexPath)
        print("backgroundCellFrame:",cell.frame)
        return cell
    }

    // MARK: - UICollectionViewDelegateFlowLayout
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 50, height: collectionView.frame.height)
    }

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

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

結果

backgroundCellFrame: (0.0, 0.0, 50.0, 568.0)
backgroundCellFrame: (52.0, 0.0, 50.0, 568.0)
backgroundCellFrame: (104.0, 0.0, 50.0, 568.0)
backgroundCellFrame: (156.0, 0.0, 50.0, 568.0)
backgroundCellFrame: (208.0, 0.0, 50.0, 568.0)
backgroundCellFrame: (260.0, 0.0, 50.0, 568.0)
backgroundCellFrame: (312.0, 0.0, 50.0, 568.0)

1 件の回答 1

2

Cellを横並びにするレイアウトの場合、Cellは、Collection Viewの横幅に対して、左揃えでも、右揃えでもなく、両端揃えになります(下図参照)。

画像の説明をここに入力

Collection Viewの横幅を、Cellの横幅で割り算して、剰余が出ると、隙間の数、均等に割り振られます。それが「謎マージン」の正体です。

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。