I am using automatically resizing cells in my project. I want to keep the cells at a minimum height
, but I cannot set a minimum height
constraint for my cells in my Content View (as it is greyed out in the Add New Constraints view:
Is there anyway to add minimum height
constraints for my cells?
To get dynamic cell heights working properly, you need to create a custom table view cell and set it up with the right Auto Layout constraints. In the project navigator, select the Views group and press Command-N to create a new file in this group.
Set your view controller constraints in the Storyboard and then create an outlet to the UITableView height constraint in your UIViewController subclass (or the constraint that controls the height of the UITableView like the distance to the bottom of the screen).
To change the height of tableView cell in ios dynamically, i.e resizing the cell according to the content available, we'll need to make use of automatic dimension property. We'll see this with the help of an sample project.
There are 2 steps to change height of a table cell without any additional code: Select your Table View from your Storyboard. In the Size Inspector change Row Height . Select your Table View Cell and while it's selected in the Size Inspector change the Row Height .
I added this constraint to my cell but in code (swift)
contentView.heightAnchor.constraint(equalToConstant: 80).isActive = true
If your cell view needs more space:
contentView.heightAnchor.constraint(greaterThanOrEqualToConstant: 80).isActive = true
When UITableViewAutomaticDimension
is enabled the system calls UITableViewCell
's systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority: method to calculate the cell height, so you can subclass UITableViewCell
and override this method to force a minimum height for the cell, in this way
class MinHeightTableViewCell: UITableViewCell {
var minHeight: CGFloat?
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
let size = super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
guard let minHeight = minHeight else { return size }
return CGSize(width: size.width, height: max(size.height, minHeight))
}
}
And then
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "minHeightCell", for: indexPath) as! MinHeightTableViewCell
cell.minHeight = 62 // change with your desidered min height
cell.textLabel?.text = "some text"
return cell
}
set a height constraint as height >= 60.0
No need to do anything
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With