如何使用heightForRowAtIndexPath方法?

hol*_*lie 4 uitableview ios swift

我试图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
    }
}
Run Code Online (Sandbox Code Playgroud)

Jua*_*rti 19

您可以设置静态高度:

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

或者使用自动维度,根据其内容自动调整每个单元格的大小:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
     return UITableViewAutomaticDimension
 }
Run Code Online (Sandbox Code Playgroud)