Joe Joe - 2 months ago 14
Swift Question

Url Image in Swift

I using the LJWebImage sample project, Which,I found from github on the following link https://github.com/likumb/LJWebImage. Project,similar to SDWebImage.I am successfully imported the sample project into my project.I am using collectionView to populating the image from plist which contain number of url links.I am trying pass the collectionView selected cellimage to my imageView but no luck so for.please someone point me the direction.my partial collectionView code below.

Thanks in Advance.

let apps: NSArray = AppInfo.appInfo()

@IBOutlet weak var imageView: UIImageView!

@IBOutlet weak var collectionView: UICollectionView!

override func viewDidLoad() {
super.viewDidLoad()

collectionView!.reloadData()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}

// MARK: - CollectionView data source


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

return apps.count
}


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath as IndexPath) as! Cell

cell.app = apps[indexPath.row] as? AppInfo

return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

if let filePath = Bundle.main.path(forResource: "apps", ofType: "plist"),
let image = UIImage(contentsOfFile: filePath) {
imageView.contentMode = .scaleAspectFit
imageView.image = image
}

}

}

Answer

You can retrieve the corresponding app object from the data source array using the indexPath.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    guard let app = apps[indexPath.row] as? AppInfo else { return }
    guard let image = UIImage(contentsOfFile: app.filePath) else { return }

    imageView.contentMode = .scaleAspectFit
    imageView.image = image
}

Or you could retrieve the cell using the indexPath and get the image from it's imageView.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    guard let cell = collectionView.cellForItem(at: indexPath) as? Cell else { return }

    imageView.contentMode = .scaleAspectFit
    imageView.image = cell.imageView.image
}