如何使用heightForRowAtIndexPath方法?

时间:2017-02-17 03:57:01

标签: ios swift uitableview

我正在尝试使用heightForRowAtIndexPath中的UITableViewController方法。但是当我尝试覆盖该方法时,它表示它不会覆盖其超类中的任何方法。

谷歌搜索引导我使用协议,这似乎可能是这个难题的一部分,但我仍然试图了解如何使用协议来使用这种方法。

非常感谢任何帮助。这是代码:(问题方法在最底层)

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
    }
}

5 个答案:

答案 0 :(得分:17)

您可以设置静态高度:

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
 }

答案 1 :(得分:3)

使用以下代码

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

答案 2 :(得分:0)

你有:

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

将其替换为:

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

[我不确定你是否需要override,但如果你这样做,编译器会告诉你,你可以把它放回去。]

答案 3 :(得分:0)

删除override,代码应该有效。这是一种可选的协议方法 - 如果您不指定它,它将根据自动布局或原型或静态单元格中设置的高度,从单元格视图计算单元格的高度。 / p>

答案 4 :(得分:0)

删除"覆盖"并且以下代码应该可以使用

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
    return 75.0
}
相关问题