1.很久沒(méi)寫(xiě)過(guò)博客了,最近項(xiàng)目要仿照微博個(gè)人主頁(yè)和網(wǎng)易云音樂(lè)個(gè)人主頁(yè)那樣,多個(gè)UITableView共用一個(gè)tableHeaderView,可以左右切換不同tableView,也可以點(diǎn)擊特定按鈕切換不同的tableView?

1.實(shí)現(xiàn)思路
在控制器中初始化一個(gè)UICollectionView,讓其左右滑動(dòng),在當(dāng)前控制器中添加三個(gè)其他控制器,把這三個(gè)控制器分別放在UICollectionViewCell中,這樣滑動(dòng)的時(shí)候就可以切換不同的控制器了,然后在其他控制器添加你需要的不同UITableView,這樣耦合度就小了。
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [[self childViewControllers] count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifer forIndexPath:indexPath];
if (!cell) {
cell = [[UICollectionViewCell alloc] init];
}
[cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
ZDTableViewController *vc = self.childViewControllers[indexPath.row];
for (UIView *view in cell.contentView.subviews) {
[view removeFromSuperview];
}
[cell.contentView addSubview:vc.view];
return cell;
}
在UICollectionView所造的控制器頂部放一個(gè)headerView高度為200(具體高度可以自己定),每個(gè)UITableView設(shè)置它的tableHeaderView高度也為200。在UITableView滑動(dòng)的時(shí)候改變headerView的位置,可以寫(xiě)一個(gè)父類UITableViewController控制器讓三個(gè)控制器集成這個(gè)父類,父類控制器寫(xiě)一個(gè)代理來(lái)傳遞UITableVIew滑動(dòng)的偏移量
UITableVIewController父類.h
#import@protocol ZDTableViewDelegate- (void)tableViewDidScroll:(UIScrollView *)scrollView;@end@interface ZDTableViewController : UITableViewController@property (nonatomic,weak)idscrollViewDelegate;
- (void)setContentOffset:(CGFloat)Offset withTag:(NSInteger)tag;
@end
父類.m
#import "ZDTableViewController.h"
@interface ZDTableViewController ()
@end
@implementation ZDTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
//每一個(gè)tableView頭部初始化一個(gè)占位view
self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, HEADERVIEW_HEIGHT)];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)setContentOffset:(CGFloat)Offset withTag:(NSInteger)tag{
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if([self.scrollViewDelegate respondsToSelector:@selector(tableViewDidScroll:)])
{
[self.scrollViewDelegate tableViewDidScroll:scrollView];
}
}
@end
具體代碼實(shí)現(xiàn)GitHub ? 代碼下載鏈接
Swift版GitHub ? ??Swift版鏈接