ios Horizontal Scrollable CollectionView中项目之间的间距问题

3gtaxfhh  于 2023-05-19  发布在  iOS
关注(0)|答案(1)|浏览(136)

我正在使用UICollectionViewCompositionalLayout构建集合视图,并希望水平滚动其项目。我有一个问题,其中有一个大的差距,一些项目滚动时。在下图中,请注意UI/UX和下一个项目之间差距。如何缩小这个空间?

下面是集合视图使用的UICollectionViewCompositionalLayout

static func createLayout() -> UICollectionViewCompositionalLayout {
    return UICollectionViewCompositionalLayout { (sectionNum, env)
        -> NSCollectionLayoutSection? in
        
        let layoutSize = NSCollectionLayoutSize(
            widthDimension: .estimated(100),
            heightDimension: .absolute(40)
        )
        
        let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: .fractionalWidth(1), heightDimension: layoutSize.heightDimension), subitems: [.init(layoutSize: layoutSize)])
        group.interItemSpacing = .fixed(10)
        
        let section = NSCollectionLayoutSection(group: group)
        section.orthogonalScrollingBehavior = .continuous
        section.contentInsets = .init(top: 0, leading: 12, bottom: 0, trailing: 12)
    
        return section
    }
}

下面是集合视图使用的单元格。

class CellOne: UICollectionViewCell {
    private lazy var label: UILabel = {
       let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textAlignment = .center
        label.font = .systemFont(ofSize: 25)
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        layer.cornerRadius = 8
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func configure(text: String) {
        self.backgroundColor = .systemRed
        label.text = text
        self.addSubview(label)
        
        let padding: CGFloat = 10
        
        NSLayoutConstraint.activate([
            label.topAnchor.constraint(equalTo: self.topAnchor),
            label.bottomAnchor.constraint(equalTo: self.bottomAnchor),
            label.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: padding),
            label.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -padding),
        ])
    }
}
ffx8fchx

ffx8fchx1#

尝试使用:

let group = NSCollectionLayoutGroup.horizontal(layoutSize: .init(widthDimension: layoutSize.widthDimension, heightDimension: layoutSize.heightDimension), subitems: [.init(layoutSize: layoutSize)])

所以我们删除:.fractionalWidth(1)并替换为layoutSize.widthDimension
目标是使组和项目大小相同。

相关问题