效果圖一
效果圖二
demo下載地址:https://github.com/ZhengYaWei1992/ZWTaobaoDetail
首先我們要知道淘寶的類似頁面,商品展示頁面是一個(gè)tabbleView晾嘶,詳情頁面是一個(gè)webView妓雾。該效果的實(shí)現(xiàn),實(shí)際上就是監(jiān)控tabbleView和wenbView的contentOffset值來調(diào)節(jié)tabbleView和webView的frame值垒迂,從而控制兩個(gè)頁面的切換展示械姻。主要實(shí)現(xiàn)代碼在ScrollView的scrollViewDidEndDragging這個(gè)代理方法中。其中ScrollDistance是一個(gè)宏常量机断,主要控制拖動(dòng)的距離楷拳。
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
CGFloat offsetY = scrollView.contentOffset.y;
if ([scrollView isKindOfClass:[UITableView class]]) {
// 能觸發(fā)翻頁的理想值:tableView整體的高度減去屏幕本身的高度
CGFloat valueNum = self.tableView.contentSize.height -self.view.frame.size.height;
if ((offsetY - valueNum) > ScrollDistance)
{
[self goToDetail]; // 進(jìn)入圖文詳情的動(dòng)畫
}
}else{// webView頁面上的滾動(dòng)
if(offsetY<0 && -offsetY > ScrollDistance)
{
[self backToFirstPage]; // 返回基本詳情界面的動(dòng)畫
}
}
}
以下兩個(gè)方法分別是進(jìn)入到webView和tabbleView具體實(shí)現(xiàn)代碼。
/**進(jìn)入到webView*/
- (void)goToDetail{
[UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
_webView.frame = CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 20);
_tableView.frame = CGRectMake(0, -self.tableView.bounds.size.height, [UIScreen mainScreen].bounds.size.width, self.tableView.bounds.size.height);
} completion:^(BOOL finished) {
}];
}
/**返回到tableView*/
-(void)backToFirstPage{
[UIView animateWithDuration:0.3 delay:0.0 options:UIViewAnimationOptionLayoutSubviews animations:^{
_tableView.frame = CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 20);
_webView.frame = CGRectMake(0, _tableView.contentSize.height, [UIScreen mainScreen].bounds.size.width, self.tableView.bounds.size.height);
} completion:^(BOOL finished) {
}];
}
除了上面的核心代碼之外吏奸,我們還要監(jiān)控webView的scrollView屬性的contentOffset值欢揖,判斷拖動(dòng)距離,在webView頂部給用戶提示奋蔚。
[_webView.scrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
if(object == _webView.scrollView && [keyPath isEqualToString:@"contentOffset"])
{
// NSLog(@"----old:%@----new:%@",change[@"old"],change[@"new"]);
[self headLabAnimation:[change[@"new"] CGPointValue].y];
}else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
// 頭部提示文本動(dòng)畫
- (void)headLabAnimation:(CGFloat)offsetY
{
self.headLabel.alpha = -offsetY/60;
self.headLabel.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2.0, -offsetY/2.f);
// 圖標(biāo)翻轉(zhuǎn)她混,表示已超過臨界值,松手就會返回上頁
if(-offsetY> ScrollDistance){
// self.headLabel.textColor = [UIColor redColor];
self.headLabel.text = @"釋放泊碑,返回詳情";
}else{
// self.headLabel.textColor = [UIColor lightGrayColor];
self.headLabel.text = @"下拉坤按,返回詳情";
}
}