根据内容使集合视图的高度动态变化

时间:2019-01-09 15:55:26

标签: ios swift

我有一个集合视图,其中包含一个宽度可变的单元格(内部有一个标签):

public class TagView: UIView {

    let textLabel: UILabel = {
        let label = UILabel()
        label.textColor = .black
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 15)
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
        setupLabel()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupView() {
        backgroundColor = #colorLiteral(red: 0.03529411765, green: 0.6862745098, blue: 0.003921568627, alpha: 1)
        backgroundColor = backgroundColor
        layer.cornerRadius = 3
        layer.masksToBounds = true
    }

    private func setupLabel() {
        addSubview(textLabel)
        textLabel.fillToSuperview(constant: 3)
    }
}

如何使集合视图的高度动态变化?问题是在初始化时我不知道应该给集合视图什么帧,所以我只给出零:

let layout = UICollectionViewFlowLayout()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)

如何使集合视图的高度动态化?

我还研究了sizeForItem方法:

public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let view = TagView()
    let data = tags[indexPath.row]
    view.textLabel.text = data
    view.layoutSubviews()
    return view.frame.size
}

但是我认为这返回的宽度和高度为零。

1 个答案:

答案 0 :(得分:1)

首先在此处设置一个假定的高度,但宽度应该已知

let collectionView = UICollectionView(frame:CGRect(x:0,y:20,width:self.view.frame.width,height:300), collectionViewLayout: layout)

然后在sizeForItemAt

let fixedWidth = (collectionView.frame.width - 40 ) / 5   // say here you need 5 items / row
let label = UILabel() 
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 15)
let si = label.sizeThatFits(CGSize(width:fixedWidth, height: CGFloat.greatestFiniteMagnitude))
// si.height is the needed height with 6 padding from top and bottom according to your constant in tagView
return CGSize(width:fixedWidth + 6.0 ,height:si.height)

对于总高度,请从上方创建一个函数,并将其与所有项目一起调用,然后添加高度并将其设置为collectionView的高度