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

时间:2015-06-09 05:13:05

标签: ios arrays uitableview swift uiimage

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

   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
    }

1 个答案:

答案 0 :(得分:1)

您的错误是您在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()
    })
相关问题