UICollectionview自调整大小的单元以恒定间距自动布局

时间:2019-12-04 19:18:27

标签: ios swift uicollectionview autolayout

我希望创建一个如下所示的uicollectionview。

Collectionview

单元格的高度将是恒定的,但是宽度应根据标签文本的长度自动更改。

FlowLayout:

        func prepareFlowLayout() -> UICollectionViewFlowLayout{
    let flowLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
    flowLayout.minimumInteritemSpacing = 3
    flowLayout.minimumLineSpacing = 3
    return flowLayout
}

标签:

let nameLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    //label.backgroundColor = .black

    return label
}()

单元格内部的自动布局:

 backgroundColor = .green
    let conView = contentView
    layer.cornerRadius = 5
    clipsToBounds = true
    conView.addSubview(nameLabel)
    NSLayoutConstraint.activate([
        nameLabel.centerXAnchor.constraint(equalTo: conView.centerXAnchor, constant: 0),
        nameLabel.centerYAnchor.constraint(equalTo: conView.centerYAnchor, constant: 0),
        nameLabel.heightAnchor.constraint(equalTo: conView.heightAnchor, multiplier: 0.8),
        nameLabel.widthAnchor.constraint(equalTo: conView.widthAnchor, multiplier: 0.8)
    ])

截至目前的结果: enter image description here

有人可以向我发送正确的方向,以找到实现这一目标的方法吗?

1 个答案:

答案 0 :(得分:0)

我所做的是使用sizeForItemAt函数根据文本检查视图的正确大小。

// MARK: - UICollectionViewDelegateFlowLayout
extension <#myCollectionVC#>: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let height: CGFloat = <#myHeight#>

        //Calculate size for current view
        let stringName: NSString = <#myObjects#>[indexPath.row] as NSString
        let width = stringName.size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14)]).width
        let padding: CGFloat = <#yourTotalPaddingSize#>
        return CGSize(width: width + padding, height: height)
    }
}

此后,您可能需要将视图向左对齐,在这种情况下,您需要创建自己的UICollectionViewFlowLayout并分配给您的collectionView(在情节提要中选择“ Collection View Flow Flow Layout”,在集合视图中,然后将类名称更改为MyCustomviewLayout):

class <#MyCustomViewLayout#>: UICollectionViewFlowLayout {
    let spacing = CGFloat(<#spacing#>) // spacing between views

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let oldAttributes = super.layoutAttributesForElements(in: rect) else {
            return super.layoutAttributesForElements(in: rect)
        }

        var newAttributes = [UICollectionViewLayoutAttributes]()
        var leftMargin = self.sectionInset.left
        for attributes in oldAttributes {
            if (attributes.frame.origin.x == self.sectionInset.left) {
                leftMargin = self.sectionInset.left
            } else {
                var newLeftAlignedFrame = attributes.frame
                newLeftAlignedFrame.origin.x = leftMargin
                attributes.frame = newLeftAlignedFrame
            }

            leftMargin += attributes.frame.width + spacing
            newAttributes.append(attributes)
        }
        return newAttributes
    }
}