当单元格具有动态宽度时,CollectionView中的间距不正确?

Tec*_*ain 8 uitableview ios uicollectionview swift

我想实现一个TokenView(芯片视图)样式视图.为此我在UITableViewCell中使用了一个集合视图,CollectionView有自定义cell.Inside自定义单元格UILabel.现在,单元格的宽度取决于内容UILabel.

下面是自定义UITableViewCell Cell的代码

import UIKit

class LanguageTableViewCell: UITableViewCell,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout{

        var arr:[String] = ["English","Intermediate","English","Intermediate","English","Intermediate","English","Intermediate","English","Intermediate","English","Intermediate","English","Intermediate","English","Intermediate","English","Intermediate","English","Intermediate","English","Intermediate"]
    @IBOutlet weak var collectionView: UICollectionView!

    override func awakeFromNib() {
        super.awakeFromNib()
        collectionView.dataSource = self
        collectionView.delegate = self
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .vertical
        self.collectionView.collectionViewLayout = layout
        // Initialization code
    }


    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "LanguageCollectionViewCell", for: indexPath) as! LanguageCollectionViewCell
        cell.setValue(lang: arr[indexPath.row],indexPath:indexPath)
        return cell
    }



    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let string = arr[indexPath.row]
        let width = (string.count * 10)
        return CGSize(width:width, height: 30)
    }

}
Run Code Online (Sandbox Code Playgroud)

上课 UICollectionViewCell

typealias Parameters = [String:Any]
import UIKit


class LanguageCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var languageLabel: UILabel!

    override func layoutSubviews() {
        super.layoutSubviews()

    }

    func setValue(lang:String ,indexPath:IndexPath) {

        if indexPath.row % 2 == 0 {
            languageLabel.backgroundColor = UIColor.gray

        }else {
            languageLabel.backgroundColor = UIColor.yellow

        }
            self.languageLabel.text = lang
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Gov*_*wat 8

在你的实施中实现 UITableViewCell Cell

  1. 子类 UICollectionViewFlowLayout
  2. 像这样添加实现:

解决方案是减少单元格间距/对齐UICollectionView单元格布局.非常简单快速的性能.基于Olloqui给出的例子

类CustomViewFlowLayout

class CustomViewFlowLayout: UICollectionViewFlowLayout {

let cellSpacing:CGFloat = 4

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
            self.minimumLineSpacing = 4.0
            self.sectionInset = UIEdgeInsets(top: 10, left: 8, bottom: 10, right: 6)
            let attributes = super.layoutAttributesForElements(in: rect)

            var leftMargin = sectionInset.left
            var maxY: CGFloat = -1.0
            attributes?.forEach { layoutAttribute in
                if layoutAttribute.frame.origin.y >= maxY {
                    leftMargin = sectionInset.left
                }
                layoutAttribute.frame.origin.x = leftMargin
                leftMargin += layoutAttribute.frame.width + cellSpacing
                maxY = max(layoutAttribute.frame.maxY , maxY)
            }
            return attributes
    }
}
Run Code Online (Sandbox Code Playgroud)

其中cellSpacing可以设置为您喜欢的任何值.这个技巧保证了单元格之间的空间完全等于cellSpacing.

UITableViewCell Cell/CollectionViewController的实现.

import UIKit

class ViewController: UIViewController , UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{

@IBOutlet weak var collectionView: UICollectionView!

var arr:[String] = ["English","Intermediate","English","English","arr","UICollectionViewFlowLayoutFlowFlowFlow","English","UICollectionViewDelegate","English","Intermediate","UIViewController","viewDidLoad","Intermediate","String","Intermediate","arr","Intermediate","UIKit","Intermediate","English","columnLayout","English","languageLabel"]

let columnLayout = CustomViewFlowLayout()

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.collectionViewLayout = columnLayout
    collectionView.contentInsetAdjustmentBehavior = .always
}


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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "chip", for: indexPath) as! LanguageCollectionViewCell
    cell.languageLabel.text = arr[indexPath.row]
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let string = arr[indexPath.row]

    // your label font.
    let font = UIFont.systemFont(ofSize: 16)
    let fontAttribute = [NSAttributedStringKey.font: font]

    // to get the exact width for label according to ur label font and Text.
    let size = string.size(withAttributes: fontAttribute)

    // some extraSpace give if like so.
    let extraSpace : CGFloat = 8.0
    let width = size.width + extraSpace
    return CGSize(width:width, height: 30)
   }
}
Run Code Online (Sandbox Code Playgroud)

上课 UICollectionViewCell

class LanguageCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var languageLabel: UILabel!

}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Man*_*nsi 5

我已经使用了一个吊舱

pod 'AlignedCollectionViewFlowLayout'
Run Code Online (Sandbox Code Playgroud)

在我使用我的课堂上UICollectionView

import AlignedCollectionViewFlowLayout
Run Code Online (Sandbox Code Playgroud)

并配置 collectionViewLayout 如下

if let fl = myCollection.collectionViewLayout as? AlignedCollectionViewFlowLayout {          
  fl.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
  fl.horizontalAlignment = .left
  fl.verticalAlignment = .top
}
Run Code Online (Sandbox Code Playgroud)

请注意,您可以使用此 Pod 设置左/右和上/下对齐方式!它对我来说就像一种魅力

我还确保添加preferredMaxLayoutWidth到我的标签中,UICollectionViewCell以便我可以修复可能的错误之一(即单元格的宽度不能大于屏幕尺寸)

class MyCollectionViewCell: UICollectionViewCell {
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        myLabel.preferredMaxLayoutWidth = UIScreen.main.bounds.size.width * 0.8
    }
}
Run Code Online (Sandbox Code Playgroud)

我的收藏结果如下:

在此处输入图片说明


Sh_*_*han 2

你能试一下吗

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let lb = UILabel()

    lb.text = arr[indexPath.row]

    lb.font = UIFont.init(name: "System", size: 17)

    lb.sizeToFit()

    return CGSize(width:lb.frame.size.width, height: 30 )
}
Run Code Online (Sandbox Code Playgroud)

//

或设置这个

layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
Run Code Online (Sandbox Code Playgroud)

并为单元格赋予标签基于 0 的前导、尾随、顶部和底部约束

注意:在这两种情况下,您都必须删除方法的实现sizeForItemAt