Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am new to iOS development. I have a problem with my cell sizing. I am not using Auto-Laylout feature. My current TableView cell looks something like this. I want to make the label size which is selected in the image to be extended dynamically based on the text content of that Label.

Thanks in advance.

like image 453
Kalai Arasi Avatar asked May 08 '15 01:05

Kalai Arasi


2 Answers

func calculateHeight(inString:String) -> CGFloat
       {
           let messageString = inString
           let attributes : [NSAttributedString.Key : Any] = [NSAttributedString.Key(rawValue:
   NSAttributedString.Key.font.rawValue) : 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
       }
like image 118
Srinivasan_iOS Avatar answered Oct 27 '22 20:10

Srinivasan_iOS


i think the swift version like below, it calculates nearer values not the exact height, for example

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 we have an array which contains string of different length

 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 the tableview and set its datasource and delegate and past the code above and run

the result will be like below

enter image description here

like image 21
Shankar BS Avatar answered Oct 27 '22 19:10

Shankar BS