我正在尝试显示项目列表。我的最终游戏是显示来自字符串数组的图像网格,这些字符串是我的 IOS 应用程序上的 URL 和文件名。
我有一个 CollectionView,它通过字符串文件名数组显示图像网格,并且有效:
数组:
var tableImages: [String] = ["car.jpg", "bus.jpg", "plane.jpg"]
有效的代码:
cell.imgCell.image = UIImage(named: tableImages[indexPath.row])
我的下一步是找出通过字符串 url 数组显示图像网格的代码。这就是我的问题。如何显示来自 url 的图像?
数组:
var tableImages: [String] = ["http://www.hotelstmarie.com/wp-content/uploads/2014/12/HSM_Guest-Rooms_1500x750-06-02-2015.jpg", "http://media-cdn.tripadvisor.com/media/photo-s/03/4f/b0/58/aviva-by-kameel.jpg"]
有效的代码:
?
注意事项:
我已经检查过关于此事的其他 stackoverflow 问题,但它们是几年前的问题,转向 swift 使它们的答案已过时。
在我弄清楚如何显示 url 图像之后,我将只做一些 if 语句来识别 url 或文件名以使其进入我的残局,但这不是这个问题的一部分。
编辑 1
围绕我上面的代码编写代码:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: CollViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollViewCell
cell.labelCell.text = tableData[indexPath.row]
cell.imgCell.image = UIImage(named: tableImages[indexPath.row])
return cell
}
编辑 2
使用 Alamofire:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: CollViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollViewCell
cell.labelCell.text = tableData[indexPath.row]
let imageUrl = NSURL(string: tableImages[indexPath.row])
cell.imgCell.af_setImageWithUrl(imageUrl, placeholderImage: nil, filter: nil, imageTransition: .CrossDissolve(0.2))
return cell
}
给出这个错误:
Value of type 'UIImageView' has no member 'af_setImageWithUrl'
最佳答案
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell: CollViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! CollViewCell
cell.labelCell.text = tableData[indexPath.row]
if let url = NSURL(string: tableImages[indexPath.row])
{
if let data = NSData(contentsOfURL: url)
{
cell.imgCell.image = UIImage(data: data)
}
}
return cell
}
关于ios - 使用来自 URL 的图像显示 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37872136/