2017-03-05 32 views
1

我使用UITableViewAutomaticDimension創建了一個TableView,但由於某種原因,最後一個之後的「額外」空單元格與最後一個包含文本的單元格具有相同的尺寸。我希望空白單元格的尺寸更小,除非填寫需要自動調整大小的文字才能放大。我該如何改變這一點?任何幫助,將不勝感激。我對此很陌生。謝謝大家!請參閱下面的TableView截圖。我已經添加了我的代碼以供參考。UITableViewAutomaticDimension使空單元格太大

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 
     } 

} 

回答

0

首先,設置從故事板默認的行高。空行將被設置爲這個高度。

然後用文本行,覆蓋此表視圖的委託方法:

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

這將迫使表視圖返回的高度指定行。通過索引路徑獲取行中的文本。計算文本高度並返回正確的行高。

這裏是計算一個字符串的幀的方法:

func boundingRect(with size: CGSize, 
      options: NSStringDrawingOptions = [], 
     attributes: [String : Any]? = nil, 
      context: NSStringDrawingContext?) -> CGRect 
0

您可以通過添加這viewDidLoad中()只是隱藏空單元格:

tableView.tableFooterView = UIView() 
相關問題