Changing the height of cell depending on text height - swift

I want to show a tableView with dynamic cell height. I found a way to change the height of my prototype cell in a tableView manually using this code. In this case the height is 400.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat (400)
}
In my cell the first part with the username (green and red) and the last part with the likes (yellow) has a fixed height with for example 60.
The height of the part in the middle (blue) should change depending on the text. So how can I do that?
I tried to get the label height with this.
override func awakeFromNib() {
super.awakeFromNib()
userComment.sizeToFit()
print(userComment.bounds.size.height)
}
But this always shows me 18. My aim is to use the first code above and return CGFloat ( 60 + 60 + dynamic label/userComment height)
This is how my tableView looks like.
extension ViewComments: UITableViewDataSource {
func tableView (_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return table.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
let video: importComment
video = table[indexPath.row]
cell.userName.text = video.userName
cell.userGroup.text = poiNavigationName.title
cell.userComment.text = video.userComment
cell.userTime.text = "\(video.userTime!)"
cell.userLikes.text = "\(video.userLikes!)"
cell.userName.text = video.userName
cell.commentId.text = video.commentId
cell.kommentarCount.text = "\(video.kommentarCount!)"
cell.buttonAction = { [unowned self] in
let selectedIndexPath = table[indexPath.row].commentId!
ViewComments.commentIDNew = selectedIndexPath
}
return cell
}
/*
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat (400)
}*/
}
Updated Picture after removing heightForRowAt and awakeFromNib

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat (400)
}
instead of using a hard coded value you can use a dynamic height.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
UITableView.automaticDimension
}
https://developer.apple.com/documentation/uikit/uitableview/1614961-automaticdimension

It seems to me you're describing something like this:
That's done entirely with the internal autolayout constraints of the prototype cell. You should not attempt to do this manually by returning a specific height for each cell; just let the runtime do it for you. It knows how to do this a lot better.

I solved it not following this tutorial and it works great. Tutorial

Related

tableview header and prototype cell showing wrong

Is there are reason why there are height differences between what is shown and what has been set as a height? also there is a space between header and prototype cell which I cannot get rid of.
extension FirstTabThirdView: UITableViewDataSource , UITableViewDelegate {
func tableView (_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = headerView
return view
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellOne", for: indexPath)
cell.textLabel?.text = "hello"
return cell
}
}

UICollectionView inside a UITableViewCell — dynamic height calculate isn't correct

I have a dynamic height collection view in table view cell. I used the approach #Igor in this topic.
UICollectionView inside a UITableViewCell -- dynamic height?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DraftCustomerTableViewCell", for: indexPath) as! DraftCustomerTableViewCell
cell.data = notificationDraftListViewData[indexPath.section]
cell.frame = tableView.bounds
cell.collectionView.reloadData()
cell.collectionViewHeightConstraint.constant = cell.collectionView.collectionViewLayout.collectionViewContentSize.height
cell.layoutIfNeeded()
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
dict[indexPath] = cell.frame.size.height
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return dict[indexPath] ?? CGFloat(450)
}
The issue is when I expand the tableview section first time, the cell's height is not calculate right. After expanding first time, the collectionView's height can been calculated correctly. I try to let my data[0].isExpand is true without taping the button and find the table view's cell height is correct. Please see the demo. Is there some approach can avoid this issue? thanks.
Demo: https://youtu.be/YJCJChCU0wQ

How to fix custom UITableViewCell dynamic height?

I'm trying to dynamically calculate the height of the custom UITableViewCell, which looks like this:
https://i.imgur.com/7U6aWgZ.png "UITableViewCell"
So the text "Hi! Could.." can be any size.
I do this in the following way:
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 150
But it doesn't help, it gives me this result:
https://i.imgur.com/c65xMMP.jpg
try giving constraints to all 4 sides of the 'Hi! Could...' UILabel and implement these UITableviewDelegate methods:-
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 150
}
and make sure you have implemented delegates and datasources correctly.

Tableview creates five rows on one row?

I have a tableView with a custom cell that I have told should give me 5 cells in return of this custom cell. The question now is that I am running the app and getting five rows on one row. I have changed from default size of cell to custom but that is nearly the only thing I have done. So now I wonder what can create this kind of problem?
The code of my tableView looks like this.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "theoryCell") as! theoryTVC
return cell
}
So the problem is you are using custom cell with custom height but you are not setting height for row in table view method.
Try this:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return 100.0 //Choose your custom row height
}

tableview persisting cell image after reloading

I have a tableview with cells that when selected displays an image within the selected cell, this image then disappears when the cell is selected again, and so on. When i press a submit button the selected cells are remembered and the tableview reloads with new data. But when doing this all the new data loads but the selected cell image persists. I have tried calling tableView.reloadData() on the main queue but it still persists. The image also persists when i press the submit button several times.
Heres my code:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return currentQuestion.answers.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return tableView.frame.height/CGFloat(currentQuestion.answers.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
setSelectedArray()
let cell: AnswersTableViewCell = tableView.dequeueReusableCell(withIdentifier: "answersTableViewCell") as! AnswersTableViewCell
let text = currentQuestion.answers[indexPath.row]
let isAnAnswer = currentQuestion.answerKeys[indexPath.row]
cell.answerTextLabel.text = text
cell.answerView.backgroundColor = UIColor.white.withAlphaComponent(0.5)
cell.contentView.sendSubview(toBack: cell.answerView)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell: AnswersTableViewCell = tableView.cellForRow(at: indexPath) as? AnswersTableViewCell {
if cell.answerImageView.image == nil {
cell.answerImageView.image = UIImage(named: "paw.png")
selected[indexPath.row] = true
} else {
cell.answerImageView.image = nil
selected[indexPath.row] = false
}
}
}
#IBAction func submitButtonWasPressed() {
if questionNumber < questions.count - 1 {
questionNumber += 1
setCurrentQuestion()
self.answersTableView.reloadData()
self.view.setNeedsDisplay()
}
}
Any help would be great. Thanks
You need to set the image back to its correct value in cellForRow. Cells in your table are reused between calls to reloadData, and since you're not touching the imageView, it's keeping its previous value. Looks to me like you want:
cell.answerImageView.image = selected[indexPath.row] ? UIImage(named: "paw.png") : nil
inside of tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath).