yangOne yangOne - 27 days ago 16
iOS Question

can't show headerVIew in tableVIew correctly

I create 2 custom tableViews when I use this code:

UITableView *mainTableView=[[MainTableView alloc]init];
[self.view addSubview:mainTableView];


The headerView I create didn't show.

UITableView *mainTableView=[[MainTableView alloc]init];
self.view=mainTableView;


This code shows the right view. What happened to my headerView?

WRONGRIGHT

UPDATE:MainTableView.m

+(instancetype)createMainView
{
return [[self alloc]init];
}
-(instancetype)initWithFrame:(CGRect)frame
{
self=[super initWithFrame:frame];
[self addmainTableView];
[self addHeadImageViewAndPageControl];
[self addTitleLabelAndNavigationButton];
return self;
}
#pragma mark -add view to main view
-(void)addHeadImageViewAndPageControl
{
UIScrollView *headImageView=[[UIScrollView alloc]init];
headImageView.frame=CGRectMake(0, 0, yScreenWidth, yScreenHeight/3);
headImageView.backgroundColor=[UIColor redColor];
self.tableHeaderView=headImageView;
//add pagecontroll
UIPageControl *headPageControl=[[UIPageControl alloc]initWithFrame:CGRectMake(-100, yScreenHeight/3-30, yScreenWidth/3, 25)];
headPageControl.numberOfPages=5;
headPageControl.pageIndicatorTintColor=[UIColor lightGrayColor];
headPageControl.currentPageIndicatorTintColor=[UIColor whiteColor];
headPageControl.currentPage=1;
[self.tableHeaderView addSubview:headPageControl];
}


this is my headerView.

Answer

The problem of your code is not set frame for Tableview. Put the code below before you add tableView to self.view.

self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

or

self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;