iPhone動態加載圖片 實例講解
iPhone動態加載圖片 實例講解是本文介紹的內容。不多說了,先來看內容。官方的例子(支持3.x以上的機子)
http://developer.apple.com/library/ios/#samplecode/LazyTableImages/Introduction/Intro.html
其實在iphone上面是實現圖片的動態加載,其實也不是很難,其中只要在代理中實現方法就可以,首先在頭文件中聲明使用到的代理:如
- @interface XXX : UIViewController<UIScrollViewDelegate>
然后在.m中實現
- //滾動停止的時候在去獲取image的信息來顯示在UITableViewCell上面
- - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
- {
- if (!decelerate)
- {
- [self loadImagesForOnscreenRows];
- }
- }
- - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
- {
- [self loadImagesForOnscreenRows];
- }
- //
- - (void)loadImagesForOnscreenRows
- {
- if ([self.entries count] > 0)
- {
- NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
- for (NSIndexPath *indexPath in visiblePaths)
- {
- AppRecord *appRecord = [self.entries objectAtIndex:indexPath.row];
- if (!appRecord.appIcon) // avoid the app icon download if the app already has an icon
- {
- [self startIconDownload:appRecord forIndexPath:indexPath];
- }
- }
- }
- }
- - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- {
- ………//初始化UITableView的相關信息
- UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
- if (cell == nil)
- {
- cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
- reuseIdentifier:CellIdentifier] autorelease];
- cell.selectionStyle = UITableViewCellSelectionStyleNone;
- }
- ……
- if (!appRecord.appIcon)//當UItableViewCell還沒有圖像信息的時候
- {
- if (self.tableView.dragging == NO && self.tableView.decelerating == NO)//table停止不再滑動的時候下載圖片(先用默認的圖片來代替Cell的image)
- {
- [self startIconDownload:appRecord forIndexPath:indexPath];
- }
- cell.imageView.image = [UIImage imageNamed:@"Placeholder.png"];
- }
- else//當appReacord已經有圖片信息的時候直接顯示
- {
- cell.imageView.image = appRecord.appIcon;
- }
- }
以上就是動態加載的主要的代碼實現(其中不包括從網絡上面下載圖片信息等操作)
因為我們創建UITableviewCell的時候是以重用的方式來創建,所以就相當于說***屏顯示的cell就是以后顯示數據和圖片的基礎,因為后面數據超出一平的時候,我們只是改變數據的顯示,并沒有為每一個cell的數據元創建相應的一個
UITableViewCell(這樣非常的浪費內存),要是我們沒有實現
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
- 和
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
代理的時候,當我們滾動UITableView的時候TableView 就是按照順序來加載圖片的信息資源,這樣當我們用力滾動Table的時候就感覺相當的卡,(其實UITableView實在一個個的顯示出cell的信息)
當我們實現了以上代理的話,就可以實現在tableView滾動停止的時候,在去加載數據信息,這樣滾動期間的tableViewCell就可以用默認的圖片信息來顯示了。
小結:iPhone動態加載圖片 實例講解的內容介紹完了,希望本文對你有所幫助!