Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

記憶體優化實作:封裝一個可重複利用 Cell 的九宮格滾動列表

編輯:Android 資訊

市面上 App 越來越多,對手機記憶體的要求也越來越高。開發時如果不在記憶體上做功課,應用很容易在低端機上被系統回收。今天我們就來看看九宮格列表該怎麼優化。先看效果:

1. 先用 XIB 自訂一個「圖片 + 文字」的 Cell

為了拿到更好的可控性,我們不走系統預設的列表元件,而是自己用 XIB 畫一個:

2. 自訂主視圖 JRMainScrollView,用 delegate/dataSource 協議驅動

做法和 UITableView 類似,不熟悉的朋友可以直接參考 UITableView 的設計。先定義資料源協議:

//資料源協議
@protocol JRMainScrollDataSource <NSObject>
//取得總數量
- (NSInteger) numberOfItems;
//取得列數
- (NSInteger) numberOfColumsOfRow;
//取得 item
- (UIView *) mainScrollView:(JRMainScrollView *)mainScrollView itemAtIndex:(NSInteger) index;
@end

再定義屬性協議:

//屬性協議
@protocol JRMainScrollDelegate <NSObject>
@optional
//取得高度
- (CGFloat) heightForItemAtView:(JRMainScrollView *) mainScrollView;
//取得寬度
- (CGFloat) widthForItemAtView:(JRMainScrollView *) mainScrollView;
//取得間距
- (CGFloat) mainScrollView:(JRMainScrollView *)mainScrollView spaceForItemWithType:(kJRMainScrollItemSpace)type;
@end

間距分成左右與上下兩種,用一個枚舉區分:

typedef enum{
    kJRMainScrollItemLeftSpace,
    kJRMainScrollItemTopSpace
} kJRMainScrollItemSpace;

3. 內部佈局:先算出所有 frame 並快取起來

注意這段程式碼裡所有尺寸參數都來自 delegate,視圖本身不持有任何魔法數字:

//加載子視圖
- (void)_loadSubViews{
    //取得總個數和列數
    NSInteger totalItems=[self.jrDataSource numberOfItems];
    NSInteger colum=[self.jrDataSource numberOfColumsOfRow];

    //取得寬度和高度
    CGFloat itemWidth=[self.jrDelegate widthForItemAtView:self];
    CGFloat itemHeigt=[self.jrDelegate heightForItemAtView:self];

    //取得間距
    CGFloat leftSpace=[self.jrDelegate mainScrollView:self spaceForItemWithType:kJRMainScrollItemLeftSpace];
    CGFloat topSpace=[self.jrDelegate mainScrollView:self spaceForItemWithType:kJRMainScrollItemTopSpace];

    CGFloat space=(kWidth-2*leftSpace-colum*itemWidth)/(colum-1)+itemWidth;

    for (int i=0;i<totalItems;i++) {
        int clo=i%colum;
        int row=i/colum;
        CGRect frame=CGRectMake(leftSpace+clo*space, 20+row*(itemHeigt+topSpace), itemWidth, itemHeigt);
        [self.array addObject:[NSValue valueWithCGRect:frame]];
    }

    self.contentSize=CGSizeMake(0, CGRectGetMaxY([[self.array lastObject] CGRectValue]));
    self.showsVerticalScrollIndicator=NO;
}

把 frame 全部預先計算並存進陣列,是後續「只渲染可見部分」的前提——滾動時就不必重算佈局了。

4. 只渲染目前視窗內的 frame

記憶體優化的關鍵就在這裡:不在螢幕可視範圍內的 Cell 完全不建立,已經建立但滾出視窗的則回收進緩衝池。

-(void)layoutSubviews{
    [super layoutSubviews];
    //循環遍歷,取出在螢幕中的 frame
    for (int i=0;i<self.array.count;i++) {
        UIView * tempView=(UIView *)self.current[@(i)];
        CGRect rect=[self.array[i] CGRectValue];
        if ([self isInScreenWith:rect]) {
            if(!tempView){   //字典裡沒有的才需要重新載入
                UIView *view=[self.jrDataSource mainScrollView:self itemAtIndex:i];
                view.frame=rect;
                [self.current setObject:view forKey:@(i)];
                [self addSubview:view];
            }
        }else if(tempView){  //存在但已滾出視野的則移除並回收
            [self.current removeObjectForKey:@(i)];
            [tempView removeFromSuperview];
            [self.pool addObject:tempView];
        }
    }

    //判斷是否在視野內:origin.y 在螢幕內,或 MAXY 在螢幕內
    - (BOOL) isInScreenWith:(CGRect) frame{
        CGFloat setMiny=self.contentOffset.y;
        CGFloat setMaxy=self.contentOffset.y+kHeight;
        BOOL condition1=frame.origin.y>=setMiny&&frame.origin.y<=setMaxy;
        BOOL condition2=CGRectGetMaxY(frame)>=setMiny&&CGRectGetMaxY(frame)<=setMaxy;
        if(condition1||condition2){
            return YES;
        }
        return NO;
    }
}

5. 用緩衝池重複利用物件

三個容器各司其職:array 存所有 frame,current 存正在顯示的 Cell,pool 則是待回收的物件池。

/** 存放 frame*/
@property(nonatomic,strong) NSMutableArray * array;
/** 存放當前顯示的物件*/
@property(nonatomic,strong) NSMutableDictionary * current;
/** 存放緩衝池物件*/
@property(nonatomic,strong) NSMutableSet * pool;

/**
 * 取得可重複利用的物件
 */
- (JRRectView *) dequeueReusedItemWithIdenty:(NSString *) identy{
    JRRectView * view=[self.pool anyObject];
    if (view!=nil) {
        [self.pool removeObject:view];
    }
    return view;
}

6. 在主控制器中掛載視圖並實作協議方法

//加載所有數據
- (void) _loadSubviews{
    //1 建立滾動視圖
    JRMainScrollView * mainScroll=[[JRMainScrollView alloc] initWithFrame:self.view.bounds];
    mainScroll.jrDataSource=self;
    mainScroll.jrDelegate=self;
    [mainScroll reloadViews];
    [self.view addSubview:mainScroll];
}

#pragma mark - 資料源方法
-(NSInteger)numberOfItems{
    return 132;
}

-(NSInteger) numberOfColumsOfRow{
    return 3;
}

-(UIView *) mainScrollView:(JRMainScrollView *)mainScrollView itemAtIndex:(NSInteger)index{
    JRRectView *cell=[mainScrollView dequeueReusedItemWithIdenty:@"test"];
    if (cell==nil) {
        cell=[[[NSBundle mainBundle] loadNibNamed:@"rect" owner:nil options:nil] lastObject];
    }
    cell.titleLabel.text=[NSString stringWithFormat:@"下載"];
    NSString * imageName=[NSString stringWithFormat:@"%d",arc4random_uniform(20)+256];
    UIImage *image=[UIImage imageNamed:imageName];
    cell.image.image=image;
    return cell;
}

#pragma mark - 協議方法
//取得高度
- (CGFloat) heightForItemAtView:(JRMainScrollView *) mainScrollView{
    return 100;
}

//取得寬度
- (CGFloat) widthForItemAtView:(JRMainScrollView *) mainScrollView{
    return 90;
}

//取得間距
- (CGFloat) mainScrollView:(JRMainScrollView *)mainScrollView spaceForItemWithType:(kJRMainScrollItemSpace)type{
    if (type==kJRMainScrollItemLeftSpace) {
        return 20;
    }else if (type==kJRMainScrollItemTopSpace){
        return 20;
    }
    return 20;
}

整體思路其實就是 UITableView 的那一套:預先算好佈局、只渲染可見區、用物件池反覆重用 Cell。順帶一提,如果圖片資源較大,還可以再加上異步解碼與降採樣,記憶體收益會更明顯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved