Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the heightForRowAtIndexPath method?

I am trying to use the heightForRowAtIndexPath method in my UITableViewController. But when I try to override the method it says that it does not override any methods from its superclass.

Googling has led me to protocols, which seem to potentially be some part of the puzzle, but I'm still trying to understand how to use a protocol to use this method.

Any help would be greatly appreciated. Here's the code: (the problem method is at the very bottom)

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
    }
}
like image 683
holycamolie Avatar asked Feb 17 '17 03:02

holycamolie


People also ask

How do I change cell height in Swift?

To change the height of tableView cell in ios dynamically, i.e resizing the cell according to the content available, we'll need to make use of automatic dimension property.

What is Uitableview in Swift?

A view that presents data using rows in a single column.


1 Answers

You can either set a static height:

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

Or use automatic dimension, with resizes every cell automatically according to its content:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { 
     return UITableViewAutomaticDimension
 }
like image 106
J Curti Avatar answered Oct 11 '22 16:10

J Curti