等间距的动态项目高度

时间:2021-05-19 09:05:51

标签: ios swift uicollectionview uicollectionviewcell

我想要实现的是这样的布局。

enter image description here

在框内会有其他内容,如图像、文本、按钮等。我想要的是使盒子的大小动态化,以便它占据其内容的高度。我想到的第一个选项是使用集合视图流布局。

经过反复试验,我最终得到了这个布局。

enter image description here

我的问题是我希望它们之间的间距相等,有什么办法可以实现吗? 我非常感谢任何建议。

到目前为止我所尝试的。

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCollectionViewCell", for: indexPath) as! MyCollectionViewCell
        cell.configure(title: data[indexPath.row].title)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}

extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let spacing: CGFloat = 10
        let numberOfItemsPerRow:CGFloat = 2
        let spacingBetweenCells:CGFloat = 10
        
        let totalSpacing = (2 * spacing) + ((numberOfItemsPerRow - 1) * spacingBetweenCells)
        
        
        let approximateWidthOfContent = view.frame.width - 32
        let size = CGSize(width: approximateWidthOfContent, height: 1000)
        let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15)]
        let estimatedFrame = NSString(string: data[indexPath.row].title).boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
        
        if let collection = self.collectionView{
            let width = (collection.bounds.width - totalSpacing)/numberOfItemsPerRow
            return CGSize(width: width, height: estimatedFrame.height + 50)
        }else{
            return CGSize(width: 0, height: 0)
        }
    }
}

我知道有类似的问题,但我找不到任何符合我要求的问题。

1 个答案:

答案 0 :(得分:0)

在学习了 raywenderlich 的教程后,我终于实现了我想要的布局,感谢那些帮助我提供重要线索的人。

我的收获

enter image description here

我遵循的说明链接是 here