ios - Swift:在 TableView 中显示来自 UIImage 数组的图像

标签 ios arrays uitableview swift uiimage

我从异步请求中获取图像并将它们添加到 [UIImage]() 以便我可以使用数组中的图像填充我的 UITableView 图像。问题是,当调用此函数时,我不断在 cellForRowAtIndexPath 函数中收到 Fatal error: Array index out of range,我怀疑这可能是因为我正在制作一个异步调用?为什么我不能将数组中的图像添加到表格 View 行?

   var recommendedImages = [UIImage]()

        var jsonLoaded:Bool = false {
            didSet {
                if jsonLoaded {

                    // Reload tableView on main thread
                    dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { // 1
                        dispatch_async(dispatch_get_main_queue()) { // 2
                            self.tableView.reloadData() // 3
                        }
                    }

                }
            }
        }

    override func viewDidLoad() {
            super.viewDidLoad()

           // ...

          let imageURL = NSURL(string: "\(thumbnail)")

          let imageURLRequest = NSURLRequest(URL: imageURL!)

          NSURLConnection.sendAsynchronousRequest(imageURLRequest, queue: NSOperationQueue.mainQueue(), completionHandler: { response, data, error in

          if error != nil {

              println("There was an error")

         } else {

              let image = UIImage(data: data)

              self.recommendedImages.append(image!)

              self.jsonLoaded = true

         }

        })

    }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        var songCell = tableView.dequeueReusableCellWithIdentifier("songCell", forIndexPath: indexPath) as! RecommendationCell

        songCell.recommendationThumbnail.image = recommendedImages[indexPath.row]


        return songCell
    }

编辑:我的 numberOfRowsInSection 方法。 recommendedTitles 来 self 排除的同一代码块。它总是 6。

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return recommendedTitles.count
    }

最佳答案

你的错误是你在numberOfRowsInSection中返回6,所以tableview知道你有6个单元格

但是,当执行cellForRowAtIndexPath时,你的图像数组是空的,所以它崩溃了。

试试这个

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return recommendedImages.count
}

也切换到主队列,这样就够了

 dispatch_async(dispatch_get_main_queue(), { () -> Void in
       self.tableView.reloadData()
    })

关于ios - Swift:在 TableView 中显示来自 UIImage 数组的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30723470/

相关文章:

objective-c - UITableView 字幕没有出现

iphone - App Store 代码与 iPhone 3G 上的 Xcode/Device 代码运行不同

ios - modal 的 Identity Inspector 不适用

javascript - 比较和索引 Javascript 数组中的正则表达式

c - 为什么 printf 无法打印 Jack 和 George 的名字?

java - 当我只更改复制的数组时,为什么我的原始数组会更改?

ios - 增加 iOS 中标题和表格单元格之间的空间

ios - 共享 .xcarchive 安全吗?

ios - Swift:Web View 不加载某些网页

ios - 将多个数组相加形成一个最终数组。调试 swift xcode