ios - 根据内容使 Collection View 高度动态

标签 ios swift

我有一个 Collection View ,其中包含一个宽度不同的单元格(其中有一个标签):

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)
    }
}

如何使 Collection View 的高度动态化?问题是在初始化时我不知道应该给 Collection View 什么框架,所以我只给零:

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

如何使 Collection View 高度动态化?

我还研究了 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
}

但我认为这会返回零宽度和高度的大小。

最佳答案

这里首先设定一个假设的高度,但是宽度应该是已知的

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 的高度

关于ios - 根据内容使 Collection View 高度动态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54113861/

相关文章:

ios - NSClassFromString 在 OC 中运行良好,但在 Swift 中崩溃

IOS Swift 如何更改 1 个表格 View 单元格

iphone - CAAnimations,并更新图层树

objective-c - 使用 Swift 的 Map api 和 Objective-c 的 valueForKeyPath 过滤 json 对象

xcode - 1 个 UIImagePickerController 和 2 个按钮

swift - 比较嵌套枚举

c# - Xamarin iOS - 模拟器 View 不刷新

ios - 在 SwiftUI 中,如何将 View 从当前位置动画到屏幕中心?

ios - 再次 : Not convertible to UInt8

swift - ios-charts 如何在方向改变时正确调整条形图的大小?