Swift中的Url图像

时间:2016-09-24 12:26:51

标签: swift uicollectionview swift3

我使用LJWebImage示例项目,我在github上找到了以下链接https://github.com/likumb/LJWebImage。项目,类似于SDWebImage.I我成功地将示例项目导入到我的项目中。我使用collectionView从plist填充包含多个url链接的图像。我正在尝试将collectionView选择的cellimage传递给我的imageView但是没有运气。请某人指出我的方向。我的部分集合查看以下代码。

先谢谢。

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
    }

    }

}

1 个答案:

答案 0 :(得分:2)

您可以使用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
}

或者你可以使用indexPath检索单元格,并从它的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
}