动态单元大小调整:覆盖Xcode故事板约束

时间:2018-06-03 09:45:01

标签: ios firebase swift4

右边,这应该根据内容给出一个调整后的单元格。但是,我的单元格的高度仍然基于故事板属性,是否可以通过覆盖storyboard属性来动态调整高度?

Storyboard's Height

func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
if let chatsText = chats[indexPath.row].message {
    let size = CGSize(width: 250, height: 1000)
        let options =   NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
        let estimatedFrame = NSString(string: chatsText).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18)], context: nil)
        return CGSize(width: view.frame.width, height: estimatedFrame.height + 20)
    }

    return CGSize(width: view.frame.width, height: 200)
}
}

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifierA, for: indexPath) as! ChatCollectionViewCell
 //   cell.messageReceived.text = chats.reversed()[indexPath.row].message
     let senderIDNumber = Auth.auth().currentUser?.uid
    if chats[indexPath.row].senderID == senderIDNumber {
    cell.messageSend.text = chats[indexPath.row].message
        if let chatsText = chats[indexPath.row].message {
            let size = CGSize(width: 250, height: 1000)
            let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
            let estimatedFrame = NSString(string: chatsText).boundingRect(with: size, options: options, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 18)], context: nil)
            cell.messageSend.frame = CGRect(x:0,y:0,width:250 + 16, height:estimatedFrame.height + 20)

         //showOutgoingMessage(text: chats[indexPath.row].message)
    }
    else {
   /* cell.messageReceived.text = chats[indexPath.row].message */
    }
    }
     return cell
    }

enter image description here

2 个答案:

答案 0 :(得分:0)

在代码中设置聊天数组后,添加以下行:

{{1}}

在设置聊天数组之前,您可能会传入sizeForItemAtIndexPath方法。 reloadData方法将重新加载collectionView并再次计算单元格大小。

答案 1 :(得分:0)

也许您忘记将集合视图的删除设置为您的布局对象。在这种情况下,您已经确认了流程布局协议:

  

UICollectionViewDelegateFlowLayout

设置集合视图代理的两种方法:

<强>第一。通过编程:

collectionView.delegate = self // if your view controller confirms UICollectionViewDelegateFlowLayout

<强>第二。在故事板中:控制并拖动到视图控制器

enter image description here

顺便说一句,如果这不是正确的ans,请将你的回购上传到公众,就像Github一样,我们会帮你修复它。