ios - 如何使用 Swift 为 UICollectionView 创建动态宽度和静态高度

标签 ios swift

我正在使用 customcell 实现 UICollection View 。在这里,我需要根据 customcell 标签字符串创建动态宽度和 static Height 需要设置。在这里,我使用下面的代码 dynamic width 不知道静态高度。如何实现?

extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return (items[indexPath.row] as String).size(withAttributes: nil)
        //return CGSize(width: label.frame.width, height: 33.5)
    }
}

最佳答案

根据要添加到 label 中的 text 计算 collectionViewCell 的 width

假设 itemsStringarray

extension ViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let textWidth = items[indexPath.row].size(withAttributes:[.font: UIFont.systemFont(ofSize: 20.0)]).width + 30.0 //30.0 is the extra padding
        let width = min(textWidth, 100.0) //100.0 is the max width
        return CGSize(width: width, height: collectionView.bounds.height)
    }
}

根据您的要求添加属性高度

关于ios - 如何使用 Swift 为 UICollectionView 创建动态宽度和静态高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57922271/

相关文章:

ios - 如何在 Swift 中的 UITableViewCell 上添加带有单击事件的按钮?

iOS7 Custom ViewController transition and Top Layout Guide

ios - 程序收到信号 : “EXC_BAD_ACCESS” with Core Data

ios - Swift 中的 UIView 动画不起作用,参数错误

ios - Touch ID 警报的 UIWindowlevel

ios - 创建IOS模拟器构建但缺少预制件

swift - Swift 中的好友类(访问内部类的私有(private)成员)

swift - 如何判断 NSWindow 是否被用于浏览文档版本(版本浏览器 UI 右侧)

ios - 为现有对象添加扩展名的 Swift 文件命名的最佳实践是什么?

ios - 实现 ScrollView