Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- /* Reusable ID = "customCell" */
- class CustomTableViewCell: UITableViewCell {
- var imageUrl: String!
- @IBOutlet weak var imageView: UIImageView!
- @IBOutlet weak var name: UILabel!
- .
- .
- .
- }
- class UIViewController: UITableDelegate, UITableDataSource {
- var people = [Person]() // populated at some point with person.name and person.imageUrl?
- .
- .
- .
- func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
- if let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as? CustomTableViewCell {
- if let person = people[indexPath.row] {
- cell.name = person.name
- if let imageUrl = person.imageUrl {
- cell.imageUrl = imageUrl
- // Download image from URL asynchronously
- URLSession.shared.dataTask(with: imageUrl) { data, response, error in
- guard let data = data, error == nil else { return }
- DispatchQueue.main.async() { () -> Void in
- if cell.imageUrl == imageUrl { // If cell url still matches downloaded image url, set to imageView. Otherwise discard (or cache)
- self.imageView.image = UIImage(data: data)
- }
- }
- }.resume()
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment