user1591668 user1591668 - 1 year ago 98
iOS Question

IOS UiTableView Cells how can I make it's height adjustable

I am using a TableView and have a TableViewCell this is my first time creating one successfully. I am getting Data via Json and populating the TableView; my issue is that all TableView Cells have the same height and since the data that I am getting back varies in size it leads to some bad looking tables Cells. For instance look at the image below how can I make it so that the TableView Cell expands if there is more data like the first cell below shows or contract if it's less data like the 2nd cell below so that there isn't so much white space shown.

enter image description here

This is how the StoryBoard looks and the element that can sometimes have a lot of data is the Post Button-label shown below . I essentially am trying to do 2 things: Expand the TableViewCell if the Post-Data is long or make the TableViewCell smaller if the Post-data is small.

enter image description here

and I have access to all elements

class HomePageTVC: UITableViewCell {

@IBOutlet weak var profile_id: UILabel!
@IBOutlet weak var comment: UIButton!
@IBOutlet weak var vote: UIButton!
@IBOutlet weak var time: UILabel!
@IBOutlet weak var post: UIButton!
@IBOutlet weak var fullname: UIButton!
@IBOutlet weak var location: UILabel!

override func awakeFromNib() {
profile_id.isHidden = true
// Initialization code

override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// post.isUserInteractionEnabled = true

// Configure the view for the selected state


Answer Source

Step1 : Apply the constraints as shown,

enter image description here

Textual representation of constraints shown in image below are :)

Vertical Constraints : V:|-[8]-[Full Name]-[8]-[time]-[8]-[TextView]-[8]-|

No height constraints on any of the component. On applying these constraints xCode will suggest you to modify the Content Compression Resistance Priority to 749 Do it !

Step 2 : uncheck the textView scrollable property

Step 3 : Set the number of lines to 0

Step 4 : In your tableView controller's ViewDidLoad() write

self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 100

Step 5 : Don't write heightForRowAtIndexPath delegate :)

Thats all :)

Hope it helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download