Expand label / cell size based on text size in UITableView Swift

I am new to iOS development. I have a problem with cell size. I do not use the Auto-Laylout . My current TableView cell looks something like this . I want the size of the label that was selected in the image to dynamically expand based on the text content of this label.

Thanks in advance.

+7
ios uitableview swift
source share
3 answers

I think the quick version, as shown below, calculates closer values, not the exact height, like

 class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { var messageArray:[String] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. messageArray = ["One of the most interesting features of Newsstand is that once an asset downloading has started it will continue even if the application is suspended (that is: not running but still in memory) or it is terminated. Of course during while your app is suspended it will not receive any status update but it will be woken up in the background", "In case that app has been terminated while downloading was in progress, the situation is different. Infact in the event of a finished downloading the app can not be simply woken up and the connection delegate finish download method called, as when an app is terminated its App delegate object doesn't exist anymore. In such case the system will relaunch the app in the background.", " If defined, this key will contain the array of all asset identifiers that caused the launch. From my tests it doesn't seem this check is really required if you reconnect the pending downloading as explained in the next paragraph.", "Whale&W", "Rcokey", "Punch", "See & Dive"] } 

in the above example we have an array containing a string of different lengths

  func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messageArray.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("CELL") as? UITableViewCell; if(cell == nil) { cell = UITableViewCell(style:UITableViewCellStyle.default, reuseIdentifier: "CELL") cell?.selectionStyle = UITableViewCellSelectionStyle.none } cell?.textLabel.font = UIFont.systemFontOfSize(15.0) cell?.textLabel.sizeToFit() cell?.textLabel.text = messageArray[indexPath.row] cell?.textLabel.numberOfLines = 0 return cell!; } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { var height:CGFloat = self.calculateHeightForString(messageArray[indexPath.row]) return height + 70.0 } func calculateHeight(inString:String) -> CGFloat { let messageString = inString let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 15.0)] let attributedString : NSAttributedString = NSAttributedString(string: messageString, attributes: attributes) let rect : CGRect = attributedString.boundingRect(with: CGSize(width: 222.0, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, context: nil) let requredSize:CGRect = rect return requredSize.height } 

try it in a new project, just add a table view and set its data source and delegate it, then run the above code and run

the result will be as below

enter image description here

+10
source share

Try overriding the methods:

 override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } 

Complete solution:

In iOS 8, Apple introduces a new feature for the UITableView, known as cells for sizing. Prior to iOS 8, if you displayed dynamic content in the form of a table using a different row, you need to calculate the row height yourself.

In short, here are the steps you need to implement when using self-sized cells:

β€’ Add auto-layout constraints in the prototype cell

β€’ Indicate the approximate RowHeight view of your table view.

β€’ Set rowHeight of your table view to UITableViewAutomaticDimension

Expressing the last two points in the code, it looks like this:

 tableView.estimatedRowHeight = 43.0; tableView.rowHeight = UITableViewAutomaticDimension 

You must add it to the viewDidLoad method.

With just two lines of code, you instruct the table view to calculate the size of the cells corresponding to its contents and make it dynamic. This cell calibration function should save a ton of code and time.

In the Attributes Inspector of your UILabel, change the Lines value to 0, so the label will automatically adjust the number of lines according to the content.

Note that the first point is required, and remember that you cannot use your own size cell without using an automatic layout.

If you notice a familiarity with automatic layout, read this, this will be enough:

https://developer.apple.com/library/mac/recipes/xcode_help-IB_auto_layout/chapters/pin-constraints.html

Or, an easier way to set the automatic layout, but maybe not as you expected, is to clear all your restrictions, go to the "Allow automatic layouts" section, and for all views, click "Reset" on the "Suggested restrictions".

+5
source share

Just add this to Viewdidload

 tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension 
+1
source share

All Articles