Swift中如何实现无需自定义类与Pod的Auto resizable collection view cells?
无需自定义类/第三方库实现自适应宽度UICollectionViewCell的方案
可以实现,仅使用系统原生API即可完成,不需要自定义UICollectionViewCell子类,也不需要引入任何Pod依赖。
实现步骤
- 注册系统默认Cell
提前给UICollectionView注册系统原生的UICollectionViewCell即可,无需创建自定义子类:
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "AutoSizeCell")- 注册系统默认Cell
- 配置CollectionView布局
你可以选择自动估算布局或者手动计算尺寸两种方案:
方案A:自动估算布局(iOS 8+支持,推荐)
给UICollectionView的FlowLayout开启自动尺寸估算:
在let layout = UICollectionViewFlowLayout() layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize // 可按需设置最小行间距、列间距等 layout.minimumInteritemSpacing = 8 layout.minimumLineSpacing = 8 collectionView.collectionViewLayout = layoutcellForItemAt方法中直接配置Cell的Label即可,注意约束要紧贴contentView:func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AutoSizeCell", for: indexPath) // 移除复用残留的旧子视图 cell.contentView.subviews.forEach { $0.removeFromSuperview() } let textLabel = UILabel() textLabel.text = yourTextArray[indexPath.item] // 替换为自己的文本数组 textLabel.font = UIFont.systemFont(ofSize: 14) textLabel.translatesAutoresizingMaskIntoConstraints = false cell.contentView.addSubview(textLabel) // 配置约束,边距可按需调整 NSLayoutConstraint.activate([ textLabel.leadingAnchor.constraint(equalTo: cell.contentView.leadingAnchor, constant: 12), textLabel.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor, constant: -12), textLabel.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 6), textLabel.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -6) ]) // 可选:限制最大宽度,避免单条文本过长撑满屏幕 textLabel.widthAnchor.constraint(lessThanOrEqualToConstant: collectionView.bounds.width - 40).isActive = true return cell }方案B:手动计算尺寸(全版本兼容)
如果需要兼容更老的系统,或者需要更精准的尺寸控制,可以手动计算文本宽度,在FlowLayout的代理方法中返回尺寸:func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let targetText = yourTextArray[indexPath.item] let textFont = UIFont.systemFont(ofSize: 14) // 和Label字体保持一致 // 计算文本宽度 let textWidth = targetText.size(withAttributes: [.font: textFont]).width // 总宽度=文本宽度+左右边距,高度可按需设置固定值或者同样计算 return CGSize(width: textWidth + 24, height: 28) }注意:使用手动计算方案时,不需要给FlowLayout设置
estimatedItemSize。- 配置CollectionView布局
内容的提问来源于stack exchange,提问作者NoName555
相关产品推荐
相关产品推荐

