2

我正在使用 UITableViewAutomaticDimension 制作 TableView,但由于某种原因,最后一个空白单元格之后的“额外”空白单元格与最后一个带有文本的单元格的尺寸相同。我希望空白单元格的大小都较小,除非填充需要自动调整大小的文本来放大它。我怎样才能改变这个?任何帮助,将不胜感激。我对此很陌生。谢谢大家!请参阅下面的 TableView 屏幕截图。我添加了我的代码以供参考。

截屏

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
        }

}
4

2 回答 2

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
于 2017-03-06T02:39:57.057 回答
0

您可以通过将其添加到 viewDidLoad() 来隐藏空单元格:

tableView.tableFooterView = UIView()
于 2017-03-06T04:13:10.053 回答