我从异步请求中获取图像并将它们添加到 [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/