Adding sub view to UITableViewHeader getting wrong width?

时间:2016-04-25 09:28:37

标签: ios objective-c iphone uitableview uitableviewsectionheader

First I build a view add to tableview as tableHeaderView

 UIView *mainHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300)];

    [self.mainViewTableView setTableHeaderView:mainHeaderView];

I could adjust the Height of mainHeaderView but I cant adjust Y position of this headView.

And I trying to add a sub view:

self.searchForShop = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.mainViewTableView.tableHeaderView.frame.size.width, 44)];
    [self.mainViewTableView addSubview:self.searchForShop];

Run app and found the subview's width is longer than tableHeadView. Do view debug and found the subview is 16 width more than tableHeadView(I run in iphone5s).

How to fix it?

enter image description here

1 个答案:

答案 0 :(得分:0)

你可以尝试这样,设置tableview的宽度可能有问题,只需将搜索栏的宽度设置为tableview的宽度

//create a tableview
tableView=[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
[self.view addSubview:self.tableView];
self.tableView.delegate=self;
self.tableView.dataSource=self;


UISearchBar *searchBar=[[UISearchBar alloc]init];
/* option 1 ->[searchBar sizeToFit]; */
/* option 2 ->*/ searchBar.frame = CGRectMake(0, 0, self.tableView.bounds.size.width, 44); //set the width how much table view has
searchBar.delegate=self;
[self.tableView setTableHeaderView:searchBar];