'How to load and show image (using UIImageView) using URL in custom table view cell in Swift?
I'm trying to load an image from a URL and display it using a UIImageView in a custom tableView cell. I'm trying to implement the following solution https://www.codingem.com/swift-load-image-from-url/ which uses a UIImageView extension.
I think the problem lies somewhere in calling the string for the loadFrom function in the tableView protocol function cellForRowAt in ViewController.swift.
The error I'm getting is "Cannot find "loadFrom" in scope in ViewController.swift where cell.myImage.image = loadFrom(URLAddress: venues[indexPath.row].image_url) is called.
venues uses the VenueInfo struct to create an array of venue information including names and image urls that are both formatted as strings that is fetched using an API request. image_url and name are variables in the VenueInfo struct.
Showing the name label (nameLabel) in CustomTableViewCell is working, but showing the UIImageView (myImage) isn't.
My code:
VenueInfo.swift
import Foundation
struct VenueInfo {
var name: String?
var image_url: String?
}
ViewController.swift
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var venues: [VenueInfo] = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTableViewCell")
tableView.delegate = self
tableView.dataSource = self
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
cell.myImage.image = loadFrom(URLAddress: venues[indexPath.row].image_url)
cell.nameLabel.text = venues[indexPath.row].name
}
}
extension UIImageView {
func loadFrom(URLAddress: String) {
guard let url = URL(string: URLAddress) else {
return
}
DispatchQueue.main.async {
[weak self] in
if let imageData = try? Data(contentsOf: url) {
if let loadedImage = UIImage(data: imageData) {
self?.image = loadedImage
}
}
}
}
}
CustomTableViewCell.swift
import UIKit
class CustomTableViewCell: UITableViewCell {
@IBOutlet var myImage: UIImageView!
@IBOutlet var nameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
