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就可以用默認的圖片信息來顯示了。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章