mr_ivan777
mr_ivan777

Reputation: 401

Swift automatic height for UITableViewCell

I am trying to make table with a large text in basic cell. Table is in UIVIewController, that implements Delegate and DataSource.

it's my ViewController:

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

let answers = ["Swift is a multi-paradigm, compiled programming language created by Apple Inc. for iOS, OS X, and watchOS development. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code than Objective-C, and also more concise. "]

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("basic", forIndexPath: indexPath) as! UITableViewCell

    cell.textLabel?.numberOfLines = 0
    cell.textLabel?.lineBreakMode = .ByWordWrapping
    cell.textLabel?.text = answers[indexPath.row]
    return cell
}

}

I set .numberOfLines = 0, but as a result, I have only 2 lines: enter image description here

How I can fix it? I hear that in IOS 8 it is much easier than in IOS < 8, and i don't need tableView.heightForRowAtIndexPath. But if I need, how to implement it a simpler?

Maybe i need to set constraints to my cell? But it's a basic Cell.

Upvotes: 2

Views: 3860

Answers (1)

winklerrr
winklerrr

Reputation: 14717

If you want your cells to automatically change the size according to its content, you should have a look at this really good answer to a similar question here on stack overflow.

From the mentioned post:

With iOS 8, Apple has internalized much of the work that previously had to be implemented by you prior to iOS 8. In order to allow the self-sizing cell mechanism to work, you must first set the rowHeight property on the table view to the constant UITableViewAutomaticDimension. Then, you simply need to enable row height estimation by setting the table view's estimatedRowHeight property to a nonzero value, for example:

self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 44.0; // set to whatever your "average" cell height is

Upvotes: 7

Related Questions