我有一个显示远程数据的应用。数据包含一个json响应,其中包含在某些事件中执行的artitsts列表。
每位艺术家都有一张我要在tableView中显示的图片。
我正在寻找一种优化的方法来缓存图像并异步创建单元格
这是我到目前为止所做的:
我的tableView
class LineupTableViewController < UITableViewController
attr_accessor :artists
#attr_accessor :table
def init
super
self.title = 'Line-up'
self.initWithNibName(nil, bundle:nil)
self.view.styleId = 'lineUpView'
self.tabBarItem = UITabBarItem.alloc.initWithTitle("LineUp", image: UIImage.imageNamed("112-group.png"), tag:2)
self
end
def viewWillAppear(animated)
view.dataSource = view.delegate = self
@artists = []
App::Persistence['event']['artists'].each do |artist|
@artists.push(Artist.new(artist)) unless artist["dj"]
end
end
def viewDidLoad
super
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight
end
def tableView(tableView, cellForRowAtIndexPath: indexPath)
artist = @artists[indexPath.row]
ArtistCell.cellForArtist(artist, indexPath:indexPath, inTableView:tableView)
end
def tableView(tableView, numberOfRowsInSection: section)
@artists.length
end
def tableView(tableView, didSelectRowAtIndexPath:indexPath)
detailViewController = ArtistsdetailViewController.alloc.initWithArtist(@artists[indexPath.row])
self.navigationController.pushViewController(detailViewController, animated:true)
end
def tableView(tableView, heightForRowAtIndexPath:indexPath)
80
end
#def reloadRowForIndexPath(indexPath)
# puts "indexPath.section #{indexPath.section}"
# self.view.reloadRowsAtIndexPaths([NSIndexPath.indexPathForRow(indexPath.row, inSection:indexPath.section)], withRowAnimation:false)
#end
end
我的自定义单元格
class ArtistCell < UITableViewCell
attr_accessor :index_path
CellId = "ArtistCellIdentifier"
def setSelected(selected, animated:animated)
super
# Configure the view for the selected state
end
def self.cellForArtist(artist, indexPath:indexPath, inTableView:tableView)
cell = tableView.dequeueReusableCellWithIdentifier(ArtistCell::CellId) || ArtistCell.alloc.initWithStyle(UITableViewCellStyleSubtitle, reuseIdentifier:CellId)
#puts "indexPath #{}"
cell.index_path = indexPath
cell.fillArtist(artist, inTableView:tableView)
cell
end
def fillArtist(artist, inTableView:tableView)
#Dispatch::Queue.concurrent.async do
# Dispatch::Queue.main.sync do
self.textLabel.text = artist.name
self.detailTextLabel.text = artist.country
JMImageCache.sharedCache.imageForURL(NSURL.URLWithString(artist.picture), completionBlock:proc {
|downloaded_image|
self.imageView.image = downloaded_image
})
# end
#end
end
end
我现在得到的是:
任何帮助解决这个问题都将非常感激 FF
答案 0 :(得分:2)
试试这个:
def fillArtist(artist, inTableView:tableView)
self.textLabel.text = artist.name
self.detailTextLabel.text = artist.country
self.imageView.setImage(nil)
JMImageCache.sharedCache.imageForURL(NSURL.URLWithString(artist.picture), completionBlock:proc { |downloaded_image|
self.imageView.image = downloaded_image
self.setNeedsLayout
})
end
end
说明:在单元格中设置NIL可确保加载新图像。 setNeedsLayout强制重新布局,从而无需点击即可显示图像。