在我的应用中,我想发送图片或发短信。在这个应用程序中,我不使用故事板,以便所有设计都是通过代码编写的,当我发送消息输出时,我使用框架在集合视图中显示消息并不像我期望的那样,你能检查我的代码并转发给我正确的方向。 这是cellForItemAtIndexPath:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let section = informations[sortedSections[indexPath.section]]
let item = section![indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ChatLogMessageCell
let date = item.value(forKey: "date") as? Date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
cell.date.text = dateFormatter.string(from: date!)
if let imageData = item.value(forKey: "image"){
let image = UIImage(data: imageData as! Data)
cell.imageView.image = image
cell.date.frame = CGRect(x: view.frame.width-60, y: 140, width: 50, height: 30)
cell.textBubleView.frame = CGRect(x: view.frame.width-230, y: 0, width: 220, height: 170)
cell.imageView.frame = CGRect(x: view.frame.width-220, y: 10, width: 180, height: 150)
//cell.messageTextView.isHidden = true
}
if let messageText = item.value(forKey: "text") as? String{
cell.messageTextView.text = messageText
let size = CGSize(width: 250, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedFrame = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 18)], context: nil)
cell.messageTextView.frame = CGRect(x: view.frame.width-estimatedFrame.width-16-16-40, y: 0, width: estimatedFrame.width+16, height: estimatedFrame.height + 20)
cell.textBubleView.frame = CGRect(x: view.frame.width-estimatedFrame.width-16-16-8-40, y: 0, width: estimatedFrame.width+16+8+48, height: estimatedFrame.height + 20)
cell.date.frame = CGRect(x: view.frame.width-60, y: estimatedFrame.height-10, width: 50, height: 30)
cell.date.text = dateFormatter.string(from: date!)
//cell.imageView.isHidden = true
}
return cell
}
这是sizeForItemAtIndexPath:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let section = informations[sortedSections[indexPath.section]]
let item = section![indexPath.row]
if let messageText = item.value(forKey: "text") as? String{
let size = CGSize(width: 250, height: 1000)
let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin)
let estimatedFrame = NSString(string: messageText).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 18)], context: nil)
return CGSize(width: view.frame.width, height: estimatedFrame.height+20)
}
if (item.value(forKey: "image") as? NSData) != nil{
return CGSize(width: 180, height: 160)
}
return CGSize(width: 0, height: 0)
}
我想要的是
但有时我得到: