模仿新浪微博个人主页 - 图片下拉放大 导航栏下拉隐藏 上拉出现
456789.gif
需求:
在实际项目开发中经常会遇到这样的需求:
1.TableView 表头视图下拉放大 松手后恢复原状
2.导航条初始时透明 随着表头视图的上滑逐渐出现 下拉表头视图时消失
最典型的例子莫过于新浪微博的个人主页。下面就跟大家简单分享下具体的实现步骤:
实现:
步骤1:
//定义表头视图属性
@interface PDMyUserViewController ()
<UIScrollViewDelegate>
@property (nonatomic,strong) UIImageView *imageView;
@end
//设置导航条为透明色
//设置导航条为透明色
-(void)setNavigationBarClear{
//给导航条设置一个空的背景图 使其透明化
[self.navigationController .navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//去除导航条透明后导航条下的黑线
[self.navigationController.navigationBar setShadowImage:[UIImage new]];
}
//添加表视图
-(void)addTableHeadView{
// 初始化表头视图
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,-kOriginalImageHeight, ktotalWidth, kOriginalImageHeight)];
self.imageView.image = [UIImage imageNamed:@"image01"];
//将表头视图添加到tablView
[self.tableView addSubview: self.imageView ];
//设置imageView的内容填充模式为ScaleAspectFill
self.imageView.contentMode = UIViewContentModeScaleAspectFill;
//设置tableView 的初始位置距离顶部200 即image的原始高度kOriginalImageHeight
self.tableView.contentInset = UIEdgeInsetsMake(kOriginalImageHeight, 0, 0, 0);
}
//在viewDidLoad中调用上面的方法
- (void)viewDidLoad {
[super viewDidLoad];
//添加表头视图
[self addTableHeadView];
//设置导航条透明化
[self setNavigationBarClear];
//设置为YES
self.automaticallyAdjustsScrollViewInsets = NO;
}
步骤二:(核心部分)
//在scrollView的代理方法中 实现如下操作
//tableView开始滚动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
NSLog(@"%f",self.tableView.contentOffset.y);
//获取tableView的Y方向偏移量
CGFloat offSet_Y = self.tableView.contentOffset.y;
向下拖动图片时
if (offSet_Y < - kOriginalImageHeight) {
//获取imageView的原始frame
CGRect frame = self.imageView.frame;
//修改imageView的Y值 等于offSet_Y
frame.origin.y = offSet_Y;
//修改imageView的height 等于offSet_Y 的绝对值 此时偏移量为负数
frame.size.height = - offSet_Y;
//重新赋值
self.imageView.frame = frame;
}
//tableView相对于图片的偏移量
CGFloat reOffset = offSet_Y + kOriginalImageHeight ;
(kOriginalImageHeight - 64)这个数值决定了导航条在图片上滑时开始出现 alpha 从 0 ~ 0.99 变化
当图片底部到达导航条底部时 导航条 aphla 变为1 导航条完全出现
CGFloat alpha = reOffset/(kOriginalImageHeight - 64);
if (alpha>=1) {
alpha = 0.99;
}
// 设置导航条的背景图片 其透明度随 alpha 值 而改变
UIImage *image = [self imageWithColor:[UIColor colorWithRed:0.227 green:0.753 blue:0.757 alpha:alpha]];
[self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
}
// 使用颜色填充图片
// 使用颜色填充图片
- (UIImage *)imageWithColor:(UIColor *)color
{
// 描述矩形
CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
// 开启位图上下文
UIGraphicsBeginImageContext(rect.size);
// 获取位图上下文
CGContextRef context = UIGraphicsGetCurrentContext();
// 使用color演示填充上下文
CGContextSetFillColorWithColor(context, [color CGColor]);
// 渲染上下文
CGContextFillRect(context, rect);
// 从上下文中获取图片
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
// 结束上下文
UIGraphicsEndImageContext();
return theImage;
}