UICollectionViewCell 根据通用应用程序中的文本量垂直调整大小

UICollectionViewCell with self-sizing vertically according to amount of text in Universal app

我是一名业余 iOS 开发人员。我在 iOS 中制作了一个简单的 Single Window Universal 应用程序来演示我的问题。在界面生成器中,我将 UICollectionView 添加到我的视图中,并赋予它特定的约束以覆盖整个屏幕。然后我制作了一个原型单元格,并使用实用程序面板将其宽度设置为 580,高度设置为 80。并为此单元格添加了一个标签,并在界面生成器本身中给出了约束。

现在,如果我运行这个项目(模拟器设备iPhone6),单元格的宽度没有根据设备的屏幕调整。它走出屏幕,显示如下:

This thing also gives me following messages in the console while running the project:

2015-11-10 11:11:15.688 uicillectionview auto-sizing[3338:262762] the behavior of the UICollectionViewFlowLayout is not defined because:
2015-11-10 11:11:15.689 uicillectionview auto-sizing[3338:262762] the item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
2015-11-10 11:11:15.689 uicillectionview auto-sizing[3338:262762] The relevant UICollectionViewFlowLayout instance is <UICollectionViewFlowLayout: 0x7f981176f810>, and it is attached to <UICollectionView: 0x7f9811862400; frame = (0 20; 375 647); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x7f981176e860>; layer = <CALayer: 0x7f9811586a60>; contentOffset: {0, 0}; contentSize: {600, 0}> collection view layout: <UICollectionViewFlowLayout: 0x7f981176f810>.
2015-11-10 11:11:15.689 uicillectionview auto-sizing[3338:262762] Make a symbolic breakpoint at UICollectionViewFlowLayoutBreakForInvalidSizes to catch this in the debugger.

现在,如果我将以下代码行添加到 ViewController.m,CollectionView 看起来完全正常,不会在控制台中给出任何错误:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    return CGSizeMake([UIScreen mainScreen].bounds.size.width-20.0, 80);

}

添加以上代码,运行ning项目后,宽度根据设备屏幕尺寸完美适配如下:

我想实现这样的功能,以便 CollectionViewCell 根据关闭可变文本的大小调整单元格的高度以完全适合它,并根据设备屏幕宽度调整宽度。有人可以帮忙吗?

只需计算文本的高度。这是方法。

func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
        let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
        label.font = font
        label.text = text
        label.sizeToFit()
        return label.frame.height
    }

那么你可以这样使用

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        let cellWidth = self.view.frame.size.width
        let cellHeight = heightForView("Your Text", font: UIFont.systemFontOfSize(17), width: cellWidth)

        return CGSize(width: cellWidth, height: cellHeight)
    }