如何自动调整包含 iOS 10 中文本的 Collection View 单元格的大小

How can I automatic size Collection View cell containing text in iOS 10

我想制作一个像 Apple 在此视频中制作的那样的集合视图 (https://developer.apple.com/videos/play/wwdc2016/219/?time=1500),其中每个单元格都包含 UILabel 中文本的一个单词,如下图所示。
在视频中,他们使用 estimatedItemSize 的新 UICollectionViewFlowLayoutAutomaticSize 常量。

在 iOS10 中执行此操作的最佳方法是什么?如何将 UICollectionViewFlowLayoutAutomaticSize 与 Storyboard 一起使用?

override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind
 kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {

    let header = collectionView.dequeueReusableSupplementaryViewOfKind(kind,      
    withReuseIdentifier: "headerId", forIndexPath: indexPath)

    return header
}

您的 UICollectionView Cell 中的 Header 可能需要此方法 还要制作这个 header 的大小,方法:

 func collectionView(collectionView: UICollectionView, layoutcollectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: view.frame.width, height: 50)
}

如果您有自己的 header class,请确保您在 viewDidLoad

中注册了它
    collectionView?.registerClass(HeaderCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")

您必须创建自己的 UICollectionViewFlowLayout 的子 class 并将 Storyboard 中 Collection View 的 Flow Layout 对象设置为此自定义 class,然后将此代码写入你的习惯 class:

override init() {
    super.init()
    estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

显然,您必须将应用的目标设置为 iOS 10

试试这个:

func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    // Calculating size of string for given fontsize
    let text = someDataArray[indexPath.row]
    let font = UIFont.boldSystemFontOfSize(15) // use your font size
    let attributedText = NSAttributedString(string: text, attributes: [NSFontAttributeName : font])
    let height = attributedText.boundingRectWithSize(CGSizeMake(self.view.bounds.width, CGFloat.max), options: [NSStringDrawingOptions.UsesFontLeading, NSStringDrawingOptions.UsesLineFragmentOrigin], context: nil).height
    let size = CGSize(width: self.view.bounds.width, height: height)
    return size
}

函数计算给定字符串、字体大小和宽度的单元格高度。 (我使用 self.view.bounds.width 所以单元格和屏幕一样宽)