*** 下拉刷新和上拉加載更多的原理***
一、介紹
在做App開發(fā)時(shí),很多時(shí)候會(huì)用到下拉刷新和上拉加載,比如我比較常用第三方MJRefresh來實(shí)現(xiàn),在這里主要討論這種效果實(shí)現(xiàn)的原理
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//NSLog(@"偏移量:%f",scrollView.contentOffset.y);
//NSLog(@"contentSize的 高:%f",scrollView.contentSize.height);
}
// 下拉刷新的原理
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
if (scrollView.contentOffset.y < - 100) {
[UIView animateWithDuration:DELAY_TIME animations:^{
// frame發(fā)生偏移,距離頂部150的距離(可自行設(shè)定)
self.tableView.contentInset = UIEdgeInsetsMake(150.0f, 0.0f, 0.0f, 0.0f);
NSLog(@"開始下拉刷新");
} completion:^(BOOL finished) {
/**
* 發(fā)起網(wǎng)絡(luò)請(qǐng)求,請(qǐng)求刷新數(shù)據(jù)
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(DELAY_TIME * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"下拉刷新結(jié)束了");
[UIView animateWithDuration:DELAY_TIME animations:^{
self.tableView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f);
}];
});
}];
}
}
// 上拉加載的原理
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
NSLog(@"%f",scrollView.contentOffset.y);
NSLog(@"%f",scrollView.frame.size.height);
NSLog(@"%f",scrollView.contentSize.height);
/**
* 關(guān)鍵-->
* scrollView一開始并不存在偏移量,但是會(huì)設(shè)定contentSize的大小,所以contentSize.height永遠(yuǎn)都會(huì)比contentOffset.y高一個(gè)手機(jī)屏幕的
* 高度;上拉加載的效果就是每次滑動(dòng)到底部時(shí),再往上拉的時(shí)候請(qǐng)求更多,那個(gè)時(shí)候產(chǎn)生的偏移量,就能讓contentOffset.y + 手機(jī)屏幕尺寸高大于這
* 個(gè)滾動(dòng)視圖的contentSize.height
*/
if (scrollView.contentOffset.y + scrollView.frame.size.height >= scrollView.contentSize.height) {
NSLog(@"%d %s",__LINE__,__FUNCTION__);
[UIView commitAnimations];
[UIView animateWithDuration:DELAY_TIME animations:^{
// frame發(fā)生的偏移量,距離底部往上提高60(可自行設(shè)定)
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 60, 0);
NSLog(@"上拉加載更多開始了");
} completion:^(BOOL finished) {
/**
* 發(fā)起網(wǎng)絡(luò)請(qǐng)求,請(qǐng)求加載更多數(shù)據(jù)
* 然后在數(shù)據(jù)請(qǐng)求回來的時(shí)候,將contentInset改為(0,0,0,0)
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(DELAY_TIME * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"上拉加載更多結(jié)束了");
[UIView animateWithDuration:DELAY_TIME animations:^{
self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}];
});
}];
}
}