Swift:在 table 视图中显示来自 UIImage 数组的图像

Swift: Display image from UIImage array in table view

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

   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 来自我排除的同一代码块。永远是 6。

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

你的错误是 return 6 in numberOfRowsInSection,所以 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()
    })