首页 > 解决方案 > 自动调整collectionview单元格不能以最小的行空间正确显示

问题描述

我有自动调整单元格集合视图,我需要在其中水平显示数据。一切正常,但我需要在两个单元格之间放置 5px 间距,因此minimumLineSpacing属性和问题开始了我的最后一个单元格由于行间距而无法正确显示。这是图像 在此处输入图像描述

这是代码

extension TopicVC : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 5
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HastagCell.identifier, for: indexPath) as! HastagCell
        let index = indexPath.row % arrClrFollowTopic.count
        cell.btnHashTag.backgroundColor = Color.custom(hexString: arrClrFollowTopic[index], alpha: 1.0).value
        if indexPath.row % 3 == 0
        {
            cell.btnHashTag.setTitle(strTitle: "#Testing 123545")
        }
        else
        {
            cell.btnHashTag.setTitle(strTitle: "#Testing")
        }
        return cell;
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    }
}

ViewDidLoad

override func viewDidLoad() {
        super.viewDidLoad()


        self.objCollectionView.register(HastagCell.nib, forCellWithReuseIdentifier: HastagCell.identifier)



        if let collectionViewLayout = self.objCollectionView.collectionViewLayout as? UICollectionViewFlowLayout{
            collectionViewLayout.estimatedItemSize = CGSize.init(width: 1.0, height: 1.0)
        }

        self.objCollectionView.delegate = self
        self.objCollectionView.dataSource = self
        // Do any additional setup after loading the view.
    }

带有自动布局的我的单元格设计

在此处输入图像描述

集合视图布局设计

在此处输入图像描述

标签: iosswift3uicollectionviewautosize

解决方案


您需要将布局的 minimumInteritemSpacing 值设置为与 minimumLineSpacing 相同。

所以添加:

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

推荐阅读