I'm creating a bubble chat like application. I created custom functions for the receiving and sending bubble chats.
After creating them, I've added them into the cells that I've created using the UITableView.
However, I am not able to set the height of the cell, depending on the height of the custom cell itself.
For example, some text passed in could be longer than the one before.
Thus I can't seem to set each cell according to the custom bubble chat height.
Please help!
This are my tableview functions
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrMsg.count
}
// second
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
// lastly created
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for:indexPath)
if arrMsg[indexPath.row]["type"] as! String == "outgoing" {
cell.contentView.addSubview(createOutGoingBubble(msg: arrMsg[indexPath.row]["message"] as! String))
}
if arrMsg[indexPath.row]["type"] as! String == "incoming" {
cell.contentView.addSubview(createIncomingBubble(mymsg: arrMsg[indexPath.row]["message"] as! String))
}
return cell
}
This is how it looks currently
How do I set the height of the cell according to the custom bubble created inside the heightforrowat function?
Probably using the line to find the height and return it:
arrMsg[indexPath.row]["message"] as! String == "outgoing"
**This is my function to create the custom bubble chats to be added into the tableviewcell
func createOutGoingBubble(msg:String) -> UIView {
let subV = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
let label = UILabel()
label.numberOfLines = 0
label.font = UIFont.systemFont(ofSize: 18)
label.textColor = .white
label.text = msg
let constraintRect = CGSize(width: 0.66 * view.frame.width,
height: .greatestFiniteMagnitude)
let boundingBox = msg.boundingRect(with: constraintRect,
options: .usesLineFragmentOrigin,
attributes: [.font: label.font],
context: nil)
label.frame.size = CGSize(width: ceil(boundingBox.width),
height: ceil(boundingBox.height))
let bubbleSize = CGSize(width: label.frame.width + 28,
height: label.frame.height + 20)
let outgoingMessageView = UIImageView(frame:
CGRect(x: view.frame.width - bubbleSize.width - 20,
y: bubbleSize.height - 25,
width: bubbleSize.width,
height: bubbleSize.height))
let bubbleImage = UIImage(named: "outgoing")?
.resizableImage(withCapInsets: UIEdgeInsets(top: 17, left: 21, bottom: 17, right: 21),
resizingMode: .stretch)
.withRenderingMode(UIImage.RenderingMode.alwaysTemplate)
outgoingMessageView.image = bubbleImage
outgoingMessageView.tintColor = UIColor(red: 0.40 , green: 0.71, blue: 1.00, alpha: 1)
subV.addSubview(outgoingMessageView)
label.center = outgoingMessageView.center
subV.addSubview(label)
return subV
}
Thanks in advance!