右边,这应该根据内容给出一个调整后的单元格。但是,我的单元格的高度仍然基于故事板属性,是否可以通过覆盖storyboard属性来动态调整高度?
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
}
答案 0 :(得分:0)
在代码中设置聊天数组后,添加以下行:
{{1}}
在设置聊天数组之前,您可能会传入sizeForItemAtIndexPath方法。 reloadData方法将重新加载collectionView并再次计算单元格大小。
答案 1 :(得分:0)