Reputation: 502
I'm trying to do a table view with a multiline label in it. Unfortunately, I had no luck with it - the cells don't seem to resize at all, although I get label to multiline.
My Swift code of TableViewController:
import UIKit
class QuestionsController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableViewAutomaticDimension
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return questionsData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("QuestionCell", forIndexPath: indexPath) as! BasicQuestionCell
let question = questionsData[indexPath.row] as Question
cell.titleLabel.text = question.content
return cell
}
}
Result:
Upvotes: 2
Views: 2297
Reputation: 1895
As you have not mention that if you are using auto layout or not, I'm assuming that you are using auto layout and have given necessary constraints to the label inside the cell.
Now just remove following two lines from viewDidLoad():
tableView.estimatedRowHeight = 100.0
tableView.rowHeight = UITableViewAutomaticDimension
And add the default function to pursue it as follows:
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return tableView.rowHeight
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
Result:
Upvotes: 6
Reputation: 3735
There are multiple things you can do to set the UICellView to match it's label's height. If you know the exact height you can simply implement:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// return the height there
return 100.0;
}
If you don't know the height, you need to get it's height at run time, and reuturn in the same function.
There are multiple ways of defining how your cells are structured. I am going to assume you're using dynamic prototypes and are simply using basic style cells.
In the above method you can do :
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let hieght = tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.frame.height {
return hieght;
} else {
print("Couln't adjust the height")
return 100.0;
}
}
If you're defining you cell's in different manner, you'd simply implement the same method, but return the height of your label within the cell.
Upvotes: 1