Swift: UITableViewCell Auto line height for Subtitle style
I have a tableView with 2 sections, the first section is for the text entered by the user earlier, the other is for a selection based on that text. The first section has the default tableViewCell style, the second section has the Subtitle style. The first section is just one cell and it dynamically depends on the amount of text without issue. The second section is a few cells, with UITableViewCell.textLabel and UITableViewCell.detailText settings. These are cells that are not the correct size, I don't know what I am doing wrong. Note: 1) I have tableView.rowHeight = UITableViewAutomaticDimension set in the viewDidLoad () method. 2) I am not using prototypes in a storyboard.
This article says that I should have constraints on the contentView. I honestly have no idea what that means. I know the limitations of setting content on a storyboard. I just don't know what he means in this context, or how I would go about it if I don't have prototypes.
Also, I have to set two reuse IDs, depending on which section it is. This way it doesn't try to reuse the cell / section that I have highlighted for user input.
With everything said in mind, here is the code I have. I'm new to Swift and developing for iOS in general, so if you have any suggestions / recommendations for refactoring, feel free to let me know. I have commented on some of the things I have tried. Setting the line height to 66 works, but that's not the goal. I want it to be dynamic because I don't know what will change later.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cellIdentifier = ""
if indexPath.section == 1 {
//tableView.rowHeight = 66
//tableView.rowHeight = UITableViewAutomaticDimension
cellIdentifier = "DistortionItem"
} else {
//tableView.rowHeight = 160
cellIdentifier = "NegativeThought"
}
var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell
if indexPath.section == 1 {
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: cellIdentifier)
}
cell.textLabel?.text = distortionslist.distortions[indexPath.row].0
cell.detailTextLabel?.font = UIFont.systemFontOfSize(10)
cell.detailTextLabel!.text = distortionslist.distortions[indexPath.row].1
cell.textLabel?.numberOfLines = 0
cell.detailTextLabel?.numberOfLines = 0
//tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
//cell.textLabel?.sizeToFit()
//cell.detailTextLabel?.sizeToFit()
} else {
if cell == nil {
//println("Cell set to default")
cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier)
}
cell.textLabel?.font = UIFont.systemFontOfSize(12)
cell.textLabel?.text = entry.thoughtText
cell.textLabel?.numberOfLines = 0
//cell.textLabel?.sizeToFit()
}
return cell
}
Screenshot example:
source to share
No one has answered this question yet
Check out similar questions: