TableView calculates wrong estimatedHeightForRowAt - swift

I'm making a chat like application, where the tableView displays dynamic height cells.
The cells have their views&subviews constrained in the right way
So that the AutoLayout can predict the height of the cells
(Top, Bottom, Leading, Trailing)
But still - as you can see in the video - the scroll indicator bar shows that wrong heights were calculated:
It recalculates the heights when a new row is appearing.
Video: https://youtu.be/5ydA5yV2O-Q
(On the second attempt to scroll down everything is fine)
Code:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
It is a simple problem. Can someone help me out?
Update 1.0
Added github:
https://github.com/krptia/Test

But still - as you can see in the video - the scroll indicator bar shows that wrong heights were calculated:
So what you want is precise content height.
For that purpose, you cannot use static estimatedRowHeight.
You should implement more correct estimation like below.
...
var sampleCell: WorldMessageCell?
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "WorldMessageCell", bundle: nil), forCellReuseIdentifier: "WorldMessageCell")
sampleCell = UINib(nibName: "WorldMessageCell", bundle: nil).instantiate(withOwner: WorldMessageCell.self, options: nil)[0] as? WorldMessageCell
}
...
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if let cell = sampleCell {
let text = self.textForRowAt(indexPath)
// note: this is because of "constrain to margins", which value is actually set after estimation. Do not use them to remove below
let margin = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 20)
// without "constrain to margins"
// let margin = cell.contentView.layoutMargins
let maxSize = CGSize(width: tableView.frame.size.width - margin.left - margin.right,
height: CGFloat.greatestFiniteMagnitude)
let attributes: [NSAttributedString.Key: Any]? = [NSAttributedString.Key.font: cell.messageLabel.font]
let size: CGRect = (text as NSString).boundingRect(with: maxSize,
options: [.usesLineFragmentOrigin], attributes: attributes, context: nil)
return size.height + margin.top + margin.bottom
}
return 100
}
This is too precise (actually real row height) and maybe slow, but you can do more approximate estimation for optimization.

You need to set tableFooterView to empty.
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
// your staff
}

According to your answer on my comment that when you set
estimatedHeightForRowAt and heightForRowAt the same values it does
work
I can confirm that you are right and that there is the problem that AutoLayout cannot calculate the right value for estimatedHeightForRowAt. So basically there are two possible things to do:
find alternative layout that will produce better results
make your own calculation for estimatedHeightForRowAt which will produce more accurate results (in general you should be able to tell what is expected height per text length and then add margins to that figure - you need to put a bit of effort to find the proper math, but it should work).

The problem is with your estimatedHeightForRowAt method. As the name implies it gives the estimated height to the table so that it can have some idea about the scrollable content until the actual content will be displayed. The more accurate value will result in a more smooth scrolling and height estimation.
You should set this value to big enough so that it can represent the height of your cell with the maximum content. In your case 650 is working fine.
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 650
}
The result would be far better with this approach.
Also, there is no need to implement delegate method for height until you want a variation on index bases. You can simply set table view property.
tableView.estimatedRowHeight = 650.0
tableView.rowHeight = .automaticDimension
Optimization
One more thing I noticed in your demo project. You've used too many if-else in your cellForRowAtIndexPath which is making it little slower. Try to minimize that. I've done some refinement to this, and it improves the performance.
Define an array which holds your message text.
var messages = ["Lorem ipsum,"many more",.....]
Replace your cellForRowAt indexPath with below:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell : WorldMessageCell
cell = tableView.dequeueReusableCell(withIdentifier: "WorldMessageCell", for: indexPath) as! WorldMessageCell
if indexPath.row < 14 {
cell.messageLabel.text = messages[indexPath.row]
}
else if indexPath.row >= 14 && indexPath.row != 27 {
cell.messageLabel.text = messages[14]
}
else if indexPath.row == 27 {
cell.messageLabel.text = messages.last
}
return cell
}

Just remove highlighted view from UITableView and it's work like a charm.
Hope it helps.

This is expected behaviour when using coarse cell height estimates (or not providing them at all, as you do). The actual height is computed only when the cells come on screen, so the travel of the scroll bar is adjusted at that time. Expect jumpy insertion/deletion animations too, if you use them.

I hope you heard about this a lot. so take short break and come back on desk and apply 2 - 3 steps for step this.
1) Make sure Autolayouts of label of Cell is setup correct like below.
2) UILabel's number of lines set zero for dynamic height of text.
3) setup automatic dimension height of cell.
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
and I believe its should be work. see results of my code.

why you add view in table view , it can also work without it. I just delete that view and change some constraints(like bottom constraints change safe area to superview) , and it works fine.
see this video
download storyboard and add it to your project and then check

Configure your tableview with these in viewDidLoad()
tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableView.automaticDimension
tableView.tableFooterView = UIView()
And you should remove both height datasource method.

What you want to do is eliminate the extra blank cells. You can do so by setting the tableFooterView to an empty UIView in the viewDidLoad method. I cloned the code from your GitHub and revised the method:
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "WorldMessageCell", bundle: nil), forCellReuseIdentifier: "WorldMessageCell")
tableView.tableFooterView = UIView()
}
setting the tableFooterView to nil worked for me as well
tableView.tableFooterView = nil

Related

How to programmatically adjust the height of a cell in a TableView if everything is created programmatically, without using a storyboard?

I've looked at a lot of examples, but somehow they don't work.
My Code Below.
Objects constraints in a custom cell:
Below is the code in the class:
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
view.addSubview(tableView)
tableView.separatorStyle = .none
tableView.estimatedRowHeight = 200
}
//tableview ->
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 340
}
There a couple of things worth addressing:
1. Do not setup your layout in layoutSubviews()
This method will get triggered multiple times everytime there has been a change to the layout made, meaning all of these constraints will be duplicated, and will eventually cause problems. Try to set them in init of the cell.
2. Do not implement heightForRowAt
When implementing this function:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 340
}
you are telling tableview to give the cell this exact size. According to documentation:
The value returned by this method takes precedence over the value in the rowHeight property.
Remove this code!
3. Set rowHeight to automatic size value
You have already correctly set the estimatedRowHeight value, but we are going to also need the rowHeight property to be set to UITableView.automaticDimension.
tableView.rowHeight = UITableView.automaticDimension
And now you should be good to go!
Bonus: Scrolling Performance improvements
Table view will benefit from any additional information on the size of the cells and you can supply that information with estimatedHeightForRowAt if you are able to calculate a better approximate than the tableView.estimatedRowHeight value you have set in the initial setup.
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
// return more accurate value here
}

Dynamic cell size with resize cell animation

I have a table view with a dynamic height of cells. Above the table is menu with buttons. When I click on the menu button, the data is loaded into the table. When data is loaded, I want to have an animation in a cell that changes the height of a cell. I wonder how this can be done?
Thanks for the help.
Swift 4
Create a boolean variable in your model for checking if your cell is expanded or not.
if you want to expand the cell as long as your label height you should connect you labels constraint to your contentView in all directions and set number of lines to 0 in your storyboard.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
details[indexPath.row].cellIsOpen = !details[indexPath.row].cellIsOpen
detailTableView.reloadData()
detailTableView.beginUpdates()
detailTableView.endUpdates()
detailViewHeightConstraint.constant = CGFloat(detailTableView.contentSize.height) // the height of whole tableView
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if details[indexPath.row].cellIsOpen {
return UITableViewAutomaticDimension // or any number you wish
} else {
return 60 // default closed cell height
}
}
}
Also you can place this two lines in your viewDidLoad() function:
detailTableView.estimatedRowHeight = 60
detailTableView.rowHeight = UITableViewAutomaticDimension

swift tableview image and label

I can't seem to figure how to have a tableview that contains a subject, body and image so that if there is not an image to have the subject and body together. see imageauto lay with table prototype
I would like the subject and body together when there is an image in the database and then if there is an image, then subject image body
pin the labels to the top and bottom of the cell. When you don't have an image you set the imageView.isHidden = true. You also return the regular cell height minus the imageView.frame.size.height in UITableViewDelegate.tableview(_:heightForRowAt:).
If you don't like approach just make two different tableViewCells and deque the one with the image when you have an image and the one without the imageView when you don't have an image.
You can do this in your dataSource methods for the tableview. Something like this should work:
//Model:
var model = [Stuff]
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "myprototype", for: indexPath)
cell.subjectLabel.text = model[indexPath.row].subject
cell.bodyLabel.text = model[indexPath.row].body
//assuming the image is an optional
if let image = model[indexPath.row].image {
cell.imageView.image = image
}
return cell
}
You might have to set the autolayout constraints for the imageView to have a low compression resistance.
You might also want to make the cells resize by implementing the following in the UITableViewDelegate methods:
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}

How to set dynamic height of custom UITabelview cell in swit

I have a UITableView that is populated with custom cells which had created by Xib(autolayout).The cell consist of multiple labels images etc and size of size of changes according to response we get from api.I have been trying hard set height dynamically. I am using following methods.
func createTabelView ()
{
let nib = UINib(nibName: "DBEventCell", bundle: nil)
self.eventTabelVew.registerNib(nib, forCellReuseIdentifier: Constants.CELL_IDENTIFIER)
self.eventTabelVew.estimatedRowHeight = 200
self.eventTabelVew.rowHeight = UITableViewAutomaticDimension
self.eventTabelVew.separatorStyle = .None //UITableViewCellSeparatorStyle.SingleLine;
self.eventTabelVew.separatorColor = UIColor.clearColor();
self.eventTabelVew.backgroundColor = UIColor.whiteColor();
self.eventTabelVew.setNeedsLayout()
self.eventTabelVew.layoutIfNeeded()
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return UITableViewAutomaticDimension
}
func tableView(tleView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
but this not working.Please do help as I am struck last from last few days.
Thanks in advance
I think you don't need this function
func tableView(tleView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
also you should check your cell autolayout constrains and adjusting properties of UI components to make it contract or expand with content also check this tutorial
https://www.appcoda.com/self-sizing-cells/

Dynamically changing height of the tableViewCell for images using UITableViewAutomaticDimension

I want to dynamically change the height of the cell such that the image fills the imageView in the width and the image maintains the aspect ratio.
I am trying to do this using UITableViewAutomaticDimension. Based on tutorials available online, this seemed to be a straightforward task. But in my case, the height of the cell doesn't adjust to perform this task. Either the image fills with aspect ratio leaving a lot of width space empty or fills the width but clips the part of the image vertically. I made sure there are leading, trailing, top and bottom constraints with respect to the cell view and also the tableView.rowHeight = UITableViewAutomaticDimension and table.estimatedRowHeight is set in viewDidLoad. I have uploaded the project at this link. Could someone please suggest what could I be missing here?
Link to GitHub
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var picTableView: UITableView!
let reuseidentifier = "dynamicCellTableViewCell"
let images = [UIImage(named: "feedImage1"), UIImage(named: "feedImage2"), UIImage(named: "feedImage3")]
override func viewDidLoad() {
super.viewDidLoad()
picTableView.rowHeight = UITableViewAutomaticDimension
picTableView.estimatedRowHeight = 1000
}
// MARK: Table View Data Source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return images.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseidentifier, forIndexPath: indexPath) as! DynamicCellTableViewCell
cell.displayImageView.image = images[indexPath.row]
return cell
}
}
I figured the solution. UIImageView when used with UITableViewAutomaticDimension only looks for the UIImage's true width and height as the size. So UIImageView adjusts its height to respond to UIImage's original height and not the scaled height for scaled width (aspectFit) to match layout constraint.
So trick is to first change the width and height of the image to match the width and height that you need in the cell. Rest of the job will be done by UITableViewAutomaticDimension. Below is the updated cellForRowAtIndex function that works now. Thanks all for giving your inputs.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseidentifier, forIndexPath: indexPath) as! DynamicCellTableViewCell
let image = images[indexPath.row]!
let newWidth = cell.displayImageView.frame.width
let scale = newWidth/image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
cell.displayImageView.image = newImage
return cell
}
You need implement next method for UITableViewController:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 1000.0;
}
Inside the method, you must know what dimension will have each cell. You must know in advance what height will have each cell.
For example, you could create an array of CGFloat saving the height will have each row, and when height change, you can update this position in array and execude tableView.reloadData().
var arrayHeight:CGFloat?
//Now fill array with height of each cell
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return arrayHeight[indexPath.row];
}
cell.updateConstraintsIfNeeded()
cell.setNeedsUpdateConstraints()
add these two lines in the cellForRowAtIndexPath delegate method
And make sure that top, bottom, right, left, constraints are set in the storyboard