在很多App中,經常存在一種需求就是,界面上下滾動時用戶的頭像也會跟著滾動,而用戶頭像在視圖向上滾動一定范圍時停留并在導航欄的位置,這里我實現了一個視圖,基本樣式如下:
基本用法如下:
1、單純的實現這一效果:
- (LEOHeaderView *)headerView {? ? if (!_headerView) {
_headerView = [[LEOHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kImageHeight)];
[_headerView setBackgroundImage:[UIImage imageNamed:@"background.jpg"]];
[_headerView setHeaderImage:[UIImage imageNamed:@"header.jpg"] text:@"leiliang"];
}? ? return _headerView;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[self.headerView reloadWithScrollView:scrollView];
}
2、給頭像添加點擊回調:
[self.headerView pressHeaderImageWithBlock:^{
NSLog(@"點擊頭像");}];
3、在視圖滾動到頂部位置時改變navigationBar的顏色:
// navigationBar 的顏色可以根據這個方法來調整// @param reachtop: YES 已經滾動到頂部, NO 在頂部以下__weak typeof(self) weakSelf = self;
[self.headerView scrollViewStateChangeWithBlock:^(BOOL reachtop) {
[weakSelf.navigationController.navigationBar leo_setBackgroundColor:reachtop ? [UIColor lightGrayColor] : [UIColor clearColor]];
}];
使用起來很簡單,只需要這幾行代碼就可以了,另外為了防止大家在使用過程中因為一些細節問題導致有bug出現,這里列出一些注意事項,只要大家按照這樣做就一定沒有問題了,具體如下:
1、在 - (void)viewWillAppear:(BOOL)animated 方法中需要調用一次 [self.headerView reloadWithScrollView:self.tableView],為了防止在剛進入這一頁面的時候視圖有偏差?
2、需要設置 tableView 的 contentInset 的 top 值為 kImageHeight - kNavigationBarHeight?
3、需要設置 tableView 的背景色為 [UIColor clearColor],否則會遮擋視圖?
4、需要設置 tableView 的頂部據屏幕頂部為 64,否則如果你想設置navigationBar為透明時頂部有留白
?5、需要將視圖插入到 tableView 的底部,這里是將視圖加在 self.view 上,并在tableView的底部,[self.view insertSubview:self.headerView belowSubview:self.tableView]?
6、需要在 - (void)scrollViewDidScroll:(UIScrollView *)scrollView 方法中調用 [self.headerView reloadWithScrollView:scrollView]?
7、需要設置 self.automaticallyAdjustsScrollViewInsets = NO; 防止滾動視圖有偏差