ios - Swift UICollectionView 水平滚动单元格标签宽度根据标签内容长度动态变化

标签 ios swift

我正在尝试使用 cell label 创建 UICollectionView 水平滚动(就像顶部菜单单行)。在这里,我需要实现不同长度的标签内容,因此基于不同长度的单元格标签应该自动调整其宽度。我正在为我的设计使用 Storyboard。

在我的代码下面

extension CameraViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.items.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.reuseID, for: indexPath) as! cameraModeCollectionViewCell
        cell.cameraMode.text = self.items[indexPath.item]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("You selected cell #\(indexPath.item)!")
    }

   func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {        
        return UIEdgeInsetsMake(0, 40, 0, 40)
   }
}

Current output Iam getting

最佳答案

实现 UICollectionViewDelegateFlowLayout 的方法 collectionView(_:layout:sizeForItemAt) 并计算 collectionViewCellwidth widthtext,您正在使用 label 填充它。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let text = self.items[indexPath.row]
    let cellWidth = text.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0
    return CGSize(width: cellWidth, height: collectionView.bounds.height)
}

在上面的代码中,我使用了 self.items[indexPath.row] 作为 text 的来源。 10.0 是添加到单元格的额外 padding

如果 items array可选unwrap self.items 的值[indexPath.row] 使用前。

关于ios - Swift UICollectionView 水平滚动单元格标签宽度根据标签内容长度动态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56628779/

相关文章:

swift - ios13 使用 PHImageManager 获取原始图像

swift - 在 ScrollView 中禁用弹跳 在 pageView Controller 中禁用水平滚动

ios - 如何在 iOS 中检测 level=2 内存警告?

ios - 配置单元格时更改 View 位置。奇怪的行为

ios - Codename One(或 ParparVM)如何将 Java 库编译成 iOS 库

iOS 导航项 - 以编程方式切换

ios - 更新 Uitableview 单元格按钮标题

ios - 使用启动屏幕在通用应用程序中禁用对 iPad Pro 的支持

ios - 将参数传递给实现协议(protocol)并快速扩展类的方法

ios - 如何让今天的日期小于 18 年