2017-02-17 71 views
1

我正嘗試在我的UITableViewController中使用heightForRowAtIndexPath方法。但是當我嘗試重寫該方法時,它說它不覆蓋它的超類中的任何方法。如何使用heightForRowAtIndexPath方法?

谷歌搜索導致我的協議,這似乎可能是困惑的一部分,但我仍然試圖瞭解如何使用協議來使用此方法。

任何幫助將不勝感激。下面的代碼:(這個問題的方法是在最底層)

import UIKit 
import Firebase 

class FruitsTableViewController: UITableViewController { 
    let rootRef = FIRDatabase.database().reference() 

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

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

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

     let busRef = rootRef.child("buses") 
     busRef.observeSingleEvent(of: .value, with: {(snapshot) in 
      if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] { 
       let bus = snapshots[Int(indexPath.row)].key 
       let busval = snapshots[Int(indexPath.row)].value as! String 
       cell.textLabel?.text = "Bus \(bus) ------- \(busval)" 
      } 
     }) 

     return cell 
    } 

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
     return "Section \(section)" 
    } 

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     return 40.0 
    } 
} 

回答

6

您可以設置靜態高度:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
{ 
    if indexPath.section == 0 { 
     return 50 
    } else { 
     return 120 
    } 
} 

或者使用自動尺寸,以重新調整每一個細胞自動根據其內容:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
    return UITableViewAutomaticDimension 
} 
+0

完美的答案,謝謝。在Main.storyboard中將行高設置爲自定義,並將高度設置爲不起作用。 –

0

您有:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 

[我不知道你是否:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 

將其替換需要override但如果你這樣做,編譯器會告訴你,你可以把它放回去。]

+0

你所要做的就是在文檔中查看它。對於這個功能,文檔在這裏:https://developer.apple.com/reference/uikit/uitableviewdelegate/1614998-tableview – matt

0

刪除override和代碼應該工作。這是一個可選的協議方法 - 如果不指定它,它將根據自動佈局或原型或靜態單元格中設置的高度,從單元格視圖計算單元格的高度。

+0

否 - 他可以刪除「覆蓋」,代碼將_compile_。但它不會工作,因爲他有錯誤的方法簽名。 – matt

0

刪除「覆蓋」和下面的代碼應該工作

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
{ 
    return 75.0 
} 
3

使用下面的代碼

func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 
{ 
    return 50.0 
}