1、準備數據面試
面試:屬性和成員變量的區別?多線程
>屬性:提供了 getter & setter 和 成員變量異步
>成員變量async
注意:真正保存數據的是「成員變量」。oop
//面試:類擴展、匿名分類,定義私有屬性或方法佈局
@interface ViewController (){成員變量能夠定義在這個位置 }url
但走向工做崗位會發現有些人會把成員變量定義在spa
@implementation ViewController {.net
Xcode7的泛型?有了泛型能夠指定容器類中對象的類型了。線程
例:NSArray <NSString *> * strings = @[ @「sun」, @「yuan」];
例:NSDictionary <NSString *, NSNumber *> *map = @{@「a」:@1 }
}
@implementation ViewController {
NSArray <NSURL *> *_urls;
}
//加載數據
- (void)loadData{
NSMutableArray *arrayM = [NSMutableArray array];
for (int i = 0; i<3; i++) {
NSString *fileName = [NSString stringWithFormat: @「%02zd.jpg」, (i + 1) ];
//提示:若是fileName 不存在 url返回 nil
NSURL *url =[ [NSBundle mainBundle] URLForResource: fileName withExtension: nil ];
[arrayM addObjecr: url];
}
_urls = arrayM.copy;
}
2、搭建界面
1.封裝一個輪播器的 視圖。 <—— urls(collectionView)
>.定義一個CZLoopView類
- (instancetype)initWithURLs: (NSArray <NSURL *> *) urls{
//必定要是UICollectionViewFlowLayout
self = [super initWithFrame: CGRectZero collectionViewLayout:[ [UICollectionViewFlowLayout alloc]init ];
if (self) {
_urls = urls;
self.dataSource = self;
//註冊class
[self registerClass: [UICollectionViewCell class] forCellWithReuseIdentifier:CZLoopViewCellID ];
}
return self;
}
2.傳遞數據。
在初始化方法中加一個urls參數
3.設置數據源。
>遵照協議
@interface CZLoopView ( ) <UICollectionViewDataSource>
>實現協議方法
1)numberOfItemsInSection…{
return _urls.count;
}
2) 定義一個cell的重用標識符 NSStirng *const CZLoopViewCellID = @「CZLoopViewCellID」;——>註冊class
cellForItemAtIndexPath:…{
//建立cell
UICollectionViewCell *cell = [collectionView dequeue…];
//註冊cell
}
4.自定義cell佈局。
>定義一個類繼承自UICollectionViewFlowLayout——>即建立一個佈局的子類。
- (void)prepareLayout { }——>」重寫控件的佈局「——>在collectionView的第一次佈局的時候,被調用,此時,collectionView的frame已經設置完畢了。
注意:這個方法很好用,不用考慮視圖view的生命週期。
5.自定義cell,顯示圖像。
>collectionViewCell 的 frame 是根據以前的 layout 已經肯定好的
//添加圖像視圖
_imageView =[ [UIImageView alloc] initithFrame: self.bounds];
[self. contentView addSubview: _imageView];
>給cell定義一個url屬性
>重寫屬性的set方法
>根據URL 獲取二進制數據
NSData *data = [NSData dataWithContentsOfURL..]
UIImage *image = [UIImage imageWithData: data];
_imageView.image = image;
>cell.url = _urls[indexPath.item];
6.實現輪播,能夠左右拖拽——>利用dispatch_async在主隊列異步,保證數據源方法執行完畢後,再滾動collectionView.
>一組實現。
scrollToItemAtIndexPath:
面試題:在開發中,何時使用過多線程,不用說AFN!
dispatch_async(dispatch_get_main_queue )——>主隊列:1)安排任務在主線程上執行。2)若是主線程當前有任務,主隊列暫時不調度任務。
提示:公司的項目中可能會出現viewDidLoad中有大量的主隊列異步的!
7.無限輪播—監聽滾動的位置
滾動中止後: 第0頁,跳轉到,第1組的第0頁
最後一頁,跳轉到第0組的最後一頁。
//代理方法---滾動視圖中止滾動。
scrollViewDidEndDecelerating...
面試題: 避免圖片少,解決快速滾動圖片輪播器的卡頓,由於跑到offset的else分支內,作offset的設置,能夠適當的將數據源放大,能夠解決卡頓。—>由於collectionView可以很好的複用。