iOS - 如何在标签文本更改后动态更新 UICollectionViewCell 大小

标签 ios swift uicollectionview uicollectionviewcell

所以我在 UICollectionView 中有一个单元格

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        var cell: myCell = collectionView.dequeueReusableCellWithReuseIdentifier("myCell", forIndexPath: indexPath) as! myCell
        // cell.descrption is an UILabel
        cell.description.text = newText
        return cell
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSizeMake(collectionView.bounds.width*0.95, collectionView.bounds.height/4)       
    }

我的问题是:

newText 是从网络上获取的。所以它是动态变化的。单元格的文本设置为 newText 后,我​​应该如何调整标签以使其具有适合“newText”的正确大小以及我应该如何调整单元格的大小并在屏幕上显示它?

我注意到 sizeForItemAtIndexPath()cellForItemAtIndexPath() 之前被调用。因此,我无法在 sizeForItemAtIndexPath() 中计算 nextText 的大小。

最佳答案

这是检查 sizeForItemAtIndexPath() 中文本大小的好方法, 因为您已经知道 sizeForItemAtIndexPath()cellForItemAtIndexPath() 之前被调用,您可以拥有一个具有相同信息的虚拟单元格。例如,您可以引用我在UITableView中使用的代码,并根据您的要求实现。

override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
    var myLabel:UILabel!
    var labelText = myTextArray[indexPath.row]
    var constraint = CGSizeMake(662, MAXFLOAT);
    var attributes = NSDictionary(dictionary: [UIFont(descriptor: UIFontDescriptorSizeAttribute, size: 12):NSFontAttributeName])
    var textSize:CGRect = NSString(string: labelText).boundingRectWithSize(constraint, options: NSStringDrawingUsesLineFragmentOrigin, attributes: attributes, context: nil)
    myLabel.text = labelText
    return myLabel.frame.size.height
}

您可以在 UICollectionView 中执行相同的操作以实现大小,因为两者共享相同的继承。 所以不会有问题。 甚至您也可以根据文本中的字符数返回自定义高度。喜欢

override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
    var myLabel:UILabel!

    var labelText = myTextArray[indexPath.row]
    if count(labelText) > 0 && count(labelText) <30
        return 40;
    else if count(labelText)>31 && count(labelText)<60
        return 70;
    //and so on
}

关于iOS - 如何在标签文本更改后动态更新 UICollectionViewCell 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30771515/

相关文章:

ios - 如何以编程方式创建展开转场

ios - App 与 iWatch 通信 : is using app group the only way?

ios - 在显示 UIAlertView 之前检查消息是否为空

swift - Xcode 7.2 无效的 Swift 支持 - SwiftSupport 文件夹丢失

ios - 如何更改动态创建的标签的属性

ios - 如何保存单元格的状态,以便当我滚动或离开页面时不会刷新单元格?

ios - UICollectionView 的弹性 header

swift - UICollectionView 数据源和委托(delegate)导致应用程序终止

ios - 如果发送短信,则保存开关状态

ios - 在没有实体 iPhone 的情况下获取 .IPA 文件