具體場(chǎng)景:
在進(jìn)入某控制器后滑動(dòng)到指定item,我是這樣操作的:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor whiteColor];
self.automaticallyAdjustsScrollViewInsets = NO;
//在這個(gè)方法里面初始化 UICollectionView(代理方法也已實(shí)現(xiàn))
[self setupSubviewsContraints];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES];
if (_currentIndex) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}
}
UICollectionView 滑動(dòng)到指定item 失敗原因分析:
UICollectionView 代理方法還沒(méi)有執(zhí)行完成就執(zhí)行如下,滑動(dòng)到某指定item代碼:
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
所以在執(zhí)行這個(gè)操作前一定要確定代理方法是否已經(jīng)執(zhí)行。
衍生疑惑:
UICollectionView 代理方法在什么時(shí)候開(kāi)始執(zhí)行
解決方法:
想了很久,沒(méi)有什么好的解決辦法,很多情況下進(jìn)入這個(gè)界面會(huì)閃一下。
最終只發(fā)現(xiàn)一種相對(duì)比較流暢的解決方案:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self.navigationController setNavigationBarHidden:YES];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (_currentIndex) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_currentIndex inSection:0];
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}
});
}
真的是投機(jī)取巧,可這是目前想到的比較好的一個(gè)解決辦法。
當(dāng)然還有一種方法,看起來(lái)還不錯(cuò):
_collectionView.contentSize = CGSizeMake(self.models.count * (self.view.frame.size.width + 20), 0);
if (_currentIndex) [_collectionView setContentOffset:CGPointMake((self.view.tz_width + 20) * _currentIndex, 0) animated:NO];
目前就只有這兩種方法。
這個(gè)問(wèn)題是在做查看相冊(cè)->預(yù)覽時(shí)候發(fā)現(xiàn)的。
另:
在獲取圖片資源asset時(shí)會(huì)遇到[[info objectForKey:PHImageResultIsDegradedKey] boolValue] Bool值
PHImageRequestID imageRequestID = [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:imageSize contentMode:PHImageContentModeAspectFill options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
}
這個(gè)回調(diào)會(huì)走兩次,Bool = Yes 是低質(zhì)量圖片,Bool = NO則為高質(zhì)量圖片
當(dāng)我只想要高質(zhì)量圖片時(shí),用了if判斷,導(dǎo)致我在由相冊(cè)->預(yù)覽會(huì)閃一下。