Ariel Gemilang
Ariel Gemilang

Reputation: 791

How to Use Table View Cell Outside Table View Function

i need to change my image in cell using view will appear. But i can't use my cell in view will appear here what i've done

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    let cell: HomeCellTableViewCell = self.tableCity.dequeueReusableCell(withIdentifier: "Cell") as! HomeCellTableViewCell
    if session == nil {
        print("first")
        cell.iconForDownload.setImage(UIImage(named: "ic_download"), for: .normal)
    } else {
        print("second")
        cell.iconForDownload.setImage(UIImage(named: "ic_next_green"), for: .normal)
    }
}

it print "first" but the image still didn't change

in my cellForRowAt :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: HomeCellTableViewCell = self.tableCity.dequeueReusableCell(withIdentifier: "Cell") as! HomeCellTableViewCell

    let city = listData[indexPath.row]
    cell.labelNameCity.text = city.region
    cell.labelNameCityJpn.text = city.regionJpn

    let stringImage = config.BASE_URL+city.imgArea
    let url = URL(string: stringImage.replacingOccurrences(of: " ", with: "%20"))
    urlDownload = config.BASE_URL+kota.urlDownload
    urlDownloadFinal = URL(string: urlDownload.replacingOccurrences(of: " ", with: "%20"))
    if session == nil {
        cell.imageCity.kf.setImage(with: url)
        cell.iconForDownload.setImage(UIImage(named: "ic_download"), for: .normal)
    } else {
        cell.imageCity.kf.setImage(with: url)
        cell.iconForDownload.setImage(UIImage(named: "ic_next_green"), for: .normal)
    }

    return cell
}

Upvotes: 1

Views: 2274

Answers (1)

Nirav D
Nirav D

Reputation: 72410

You need to use cellForRow(at:) to get the cell it will return optional UITableViewCell so use if let or guard let to wrapped the optional.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)

    let indexPath = IndexPath(row: 0, section: 0) //Set your row and section
    if let cell = tableView.cellForRow(at: indexPath) as? HomeCellTableViewCell {
        //access cell
    }
}

Note: The batter approach is to set your datasource array and simply reload the affected table rows using reloadRows(at:with:).

let indexPath = IndexPath(row: 0, section: 0) //Set your row and section
self.tableView.reloadRows(at: [indexPath], with: .automatic)

Upvotes: 5

Related Questions