【问题标题】:How do I set a different height for each UICollectionViewCell如何为每个 UICollectionViewCell 设置不同的高度
【发布时间】:2015-06-22 03:04:19
【问题描述】:

我觉得这应该比现在容易得多。我想要做的就是为我的每个集合视图的单元格设置不同的高度(取决于每个单元格内标签的大小)。我正在使用sizeForItemAtIndexPath,但问题是在创建单元格之前确定高度。

我现在拥有的:

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

    // target width of each cell - widht of the collectionView
    let targetWidth: CGFloat = collectionView.frame.width - 20.0

    // setup a prototype cell
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCustomCellIdentifier", forIndexPath: indexPath) as! MyCustomCell

    // for the sake of simplicity, let's just assume data is coming from somewhere else
    cell.nameLabel.text = data.name
    cell.notesLabel.text = data.notes

    // resize - layoutSubviews in LocationCell controller
    cell.layoutIfNeeded()

    // get the size based on constraints
    var size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)

    // force width
    size.width = targetWidth

    return size
}

不工作的是dequeueReusableCellWithReuseIdentifier。我猜这是因为UICollectionViewCell 还不可用?我也试过registerClass 来得到它,但这似乎也不起作用。 :(

有没有更简单的方法可以完全做到这一点?我需要做的就是在创建单元格之前弄清楚它的高度。我需要UICollectionViewCell 子类的实例才能启动(这样我实际上可以访问标签并尝试确定高度)。被困在这几个小时了。 :/

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    使用这个方法

     func heightForComment(comment:NSString,font: UIFont, width: CGFloat) -> CGFloat {
            let rect = NSString(string: comment).boundingRectWithSize(CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
            return ceil(rect.height)
    }
    

    【讨论】:

    • 谢谢。这行得通。似乎我仍然应该能够根据实际单元格计算高度,或者应该更直观,但我想情况并非如此。 :( 谢谢!
    【解决方案2】:

    这不是正确的方法,但对我有用

    使用该函数获取文本的大小

    func labelSize(texto: NSString) -> CGRect {
            var atributos = [NSFontAttributeName: UIFont.systemFontOfSize(17)]
            var labelSize = texto.boundingRectWithSize(CGSizeMake(280, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: atributos, context: nil)
            return labelSize
        }
    

    【讨论】:

    • 听起来这样可能有效,所以谢谢。我只是担心这在复杂的布局中会变得非常混乱。必须有一种方法,因为到处都在使用具有不同大小单元格的集合视图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    相关资源
    最近更新 更多