2

I'm making a TableView with UITableViewAutomaticDimension but for some reason the "extra" blank cells after the last one are the same dimensions as the last cell with text in it. I want the blank cells to all be a smaller size unless filled with text that requires the auto sizing to enlarge it. How can I change this? Any help would be appreciated. I'm very new to this. Thanks everybody! See below for a screenshot of the TableView. I've added my code for reference.

screenshot

Import UIKit

class LoLFirstTableViewController: UITableViewController {

    var tasks:[Task] = taskData

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 60.0
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tasks.count
    }

    @IBAction func cancelToLoLFirstTableViewController(_ segue:UIStoryboardSegue) {
    }

    @IBAction func saveAddTask(_ segue:UIStoryboardSegue) {
        if let AddTaskTableViewController = segue.source as? AddTaskTableViewController {

            if let task = AddTaskTableViewController.task {
                tasks.append(task)

                let indexPath = IndexPath(row: tasks.count-1, section: 0)
                tableView.insertRows(at: [indexPath], with: .automatic)
            }
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
        -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TaskCell", for: indexPath)
        as! TaskCell

        let task = tasks[indexPath.row] as Task
            cell.task = task
        return cell
        }

}
Bob F.
  • 93
  • 1
  • 11

2 Answers2

0

First, you set the default row height from storyboard. The empty row will be set to this height.

Then for the rows with texts, override this table view's delegate method:

optional func tableView(_ tableView: heightForRowAt indexPath: IndexPath) -> CGFloat

This will force the table view to return the height for the specified row. Get the text from the row by its index path. Calculate the text height and return the correct row height.

Here is the method to calculate a string's frame:

func boundingRect(with size: CGSize, 
          options: NSStringDrawingOptions = [], 
       attributes: [String : Any]? = nil, 
          context: NSStringDrawingContext?) -> CGRect
The Mach System
  • 6,703
  • 3
  • 16
  • 20
0

You can just hide the empty cells by adding this to viewDidLoad():

tableView.tableFooterView = UIView()
Stefan S
  • 721
  • 10
  • 13