I have a tableView and a UITextView inside it. I am trying to add data from JSON to the table view but it is not shrinking/expanding according to size. I have tried a lot of forums and methods.
The main problem is - if it starts expanding/shrinking with height, it stops shrinking/expanding and vice versa. Bot height and width are not working.
This is because, when I set the trailing and leading constraints of the UITextView to the cell, it starts working with height but stops working with width. When I remove the leading/trailing constraints, the content of the UITextView goes beyond the screen and does not come as multiline i.e. does not expand with height. I have tried -
How do I size a UITextView to its content?
How to resize table cell based on textview?
and a lot many like these.
A little of my code-
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Message") as! TextViewCell
cell.customTextView.textColor = UIColor.white
// Give a source to table view cell's label
cell.customTextView.text = requestResponseArr[indexPath.row]
cell.translatesAutoresizingMaskIntoConstraints = true
cell.sizeToFit()
if (indexPath.row % 2 == 0) {
cell.customTextView.backgroundColor = ConstantsChatBot.Colors.iMessageGreen
cell.customTextView.textAlignment = .right
} else {
cell.customTextView.backgroundColor = ConstantsChatBot.Colors.ButtonBlueColor
cell.customTextView.textAlignment = .left
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
And in viewDidLoad()-
override func viewDidLoad() {
// RandomEstimatedRowHeight
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 300
}
I do not want the textview to be editable. Please reply with swift as I am not familiar with Objective C. Thanks
EDIT: Custom cell code
class TextViewCell: UITableViewCell {
@IBOutlet weak var customTextView: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
customTextView.isScrollEnabled = false
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}