By right, this should give a adjusted cell based on the content.However, the height of my cell is still based on the storyboard property and is there a way to let the height adjust dynamically by overriding the storyboard property?
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
}
Just after you set your chats array in your code add the following line :
yourCollectionViewName.reloadData()
You probably pass into your sizeForItemAtIndexPath method before setting your array of chat. reloadData method will reload your collectionView and calculate cell size again.
maybe you forget to set collection view's delete to your layout object. in this case, you've confirmed flow layout protocol already:
UICollectionViewDelegateFlowLayout
two ways to set collection view's delegate:
1st. by programming:
collectionView.delegate = self // if your view controller confirms UICollectionViewDelegateFlowLayout
2nd. in storyboard: control and drag to the view controller
BTW, if this is not the right ans, please upload your repo to public, like Github, we would help you fix it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.