【发布时间】:2015-09-16 07:55:33
【问题描述】:
我目前正在使用我的数据库中的信息(一些带有图像及其名称的产品)开发一个 JSON TableView。一切都很好,但是当我向下(或向上)滚动时速度很慢。我已经对这个主题进行了很多研究,但是我尝试了他们的代码,但我仍然不知道如何将图像存储在缓存中以加速 TableView。
这是我的代码:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! BuscarCellTableViewCell
if searchController.active {
cell.nombre.text = searchResults[indexPath.row].nombre
cell.marca.text = searchResults[indexPath.row].marca
if let url = NSURL(string: searchResults[indexPath.row].imagen) {
if let data = NSData(contentsOfURL: url) {
cell.imagen.image = UIImage(data: data)
}
}
}
else {
cell.nombre.text = productos[indexPath.row].nombre
cell.marca.text = productos[indexPath.row].marca
if let url = NSURL(string: productos[indexPath.row].imagen) {
if let data = NSData(contentsOfURL: url) {
cell.imagen.image = UIImage(data: data)
}
}
}
return cell
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
// Define the initial state (Before the animation)
cell.alpha = 0.25
// Define the final state (After the animation)
UIView.animateWithDuration(1.0, animations: { cell.alpha = 1 })
}
func getLatestLoans() {
let request = NSURLRequest(URL: NSURL(string: LoadURL)!)
let urlSession = NSURLSession.sharedSession()
let task = urlSession.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
let res = response as! NSHTTPURLResponse!
var err: NSError?
if error != nil {
println(error.localizedDescription)
}
// Parse JSON data
self.productos = self.parseJsonData(data)
// Reload table view
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
})
task.resume()
}
func parseJsonData(data: NSData) -> [Producto] {
var productos = [Producto]()
var error:NSError?
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary
// Return nil if there is any error
if error != nil {
println(error?.localizedDescription)
}
// Parse JSON data
let jsonProductos = jsonResult?["lista_productos"] as! [AnyObject]
for jsonProducto in jsonProductos {
let producto = Producto()
producto.nombre = jsonProducto["nombre"] as! String
producto.imagen = jsonProducto["imagen"] as! String
productos.append(producto)
}
return productos
}
从 JSON 文件中向下滚动“产品”时如何加快 TableView 的速度?
提前致谢,
问候。
【问题讨论】:
标签: ios json swift uitableview