Change label text when height expand of cell of tableView in swift

1k views Asked by At

I am new in IOS and i am using swift.I want to change the text of label when height of cell expand.Please tell me how to change text when height expand of cell in swift.

import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var selectedIndex = -1
    var height = 54
    // Data model: These strings will be the data for the table view cells
    let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    // cell reuse id (cells that scroll out of view can be reused)
    let cellReuseIdentifier = "cell"

    // don't forget to hook this up from the storyboard
    @IBOutlet var tableView: UITableView!
    override func viewDidLoad()
    {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }

    // number of rows in table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return 2
    }

    // create a cell for each table view row
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        // create a new cell if needed or reuse an old one
        let cell:Cell1 = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! Cell1!
        cell.textLabel?.text = "-"
        return cell
    }

    // method to run when table view cell is tapped

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         let cell:Cell1 = self.tableView.dequeueReusableCell(withIdentifier: "cell") as! Cell1!
        if(selectedIndex == indexPath.row)
        {
            height = 216

            cell.textLabel?.text = "+"
        }else{
             height = 54
             cell.textLabel?.text = "/"
        }
        return CGFloat(height)
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        print("You tapped cell number \(indexPath.row).")

        if(selectedIndex == indexPath.row)
        {
            selectedIndex = -1
        }
        else
        {

            selectedIndex = indexPath.row
        }
    }
}
1

There are 1 answers

0
Shezad On

In your code you are trying to dequeue the cell again in your heightForRowAt function, I think that's your issue.

so try replace your heightForRowAt function with the below code.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
      let cell = tableView.cellForRow(at: indexPath) 
    if(selectedIndex == indexPath.row)
    {
        height = 216

        cell.textLabel?.text = "+"
    }else{
         height = 54
         cell.textLabel?.text = "/"
    }
    return CGFloat(height)
}