ios - 使用来自 URL 的图像显示 UIImage

标签 ios xcode swift uiimage

我正在尝试显示项目列表。我的最终游戏是显示来自字符串数组的图像网格,这些字符串是我的 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/

相关文章:

c++ - 将 C++ 库与 Objective-C 应用程序链接和使用

ios - ScrollView 内容未填充 SwiftUI

ios - 如何从外部更新 SwiftUI View 状态(例如 UIViewController)

ios - 如何在 Xcode/Swift 的 ScrollView 中将多个图像居中

iphone - bool _WebTryThreadLock(bool), 0xa871560 : Multiple locks on web thread not allowed! 请提交错误。现在崩溃

ios - 即使在小代码示例中将 unowned 与 Protocol 一起使用时也会发生 Swift Leak

ios - Xcode9 无法读取 swift2。 Xcode 8.2 无法在 ios10.3 上运行。怎么办?

swift - 在 Swift 中子类化 SCNScene - 覆盖 init

iOS didFinishLaunchingWithOptions : no URL although the app is opened by tapping a link

ios - Xcode iOS bundle 包含不允许的文件 'Frameworks'