2017-02-17 74 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 
}