我目前正在尝试以编程方式在带有tableview和searchbar的ios中创建一个searchview。 tableview的工作方式和预期的一样,但是搜索栏在屏幕左侧,只是它最后一个可见的像素。请告诉我我错在哪里。以编程方式创建searchview ios
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
//init array item for table view
self.timeZoneNames = [NSMutableArray array];
for(int i = 0; i < 100; i++)
{
[self.timeZoneNames addObject:[NSString stringWithFormat:@"a %d", i]];
}
//init rectangel that store table view's frame
UIScreen *mainScreen;
CGRect rect = CGRectMake(0, 44, [mainScreen applicationFrame].size.width,[mainScreen applicationFrame].size.height);
//init search bar
UISearchBar *search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [mainScreen applicationFrame].size.width, 44)];
//init search controller that handle search bar
//UISearchDisplayController *searchController = [[UISearchDisplayController alloc] initWithSearchBar:search contentsController:self];
//searchController.delegate = self;
//searchController.searchResultsDataSource = self;
//UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [mainScreen applicationFrame].size.width, 44)];
//[view addSubview:search];
//init table view, add search bar on top of table view and reload data
UITableView *table = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
table.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
table.dataSource = self;
table.delegate = self;
//table.tableHeaderView = search;
[table reloadData];
//set table view to be this controller's view
//self.view = table;
self.view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [mainScreen applicationFrame].size.width, [mainScreen applicationFrame].size.height)];
self.view.backgroundColor = [UIColor blackColor];
[self.view addSubview:table];
[self.view addSubview:search];
}
为什么使用'[mainScreen applicationFrame]'?相反,只需尝试'self.view.bounds'。你不必为'self.view'再次分配内存。您也可以删除该行。 – iDev
感谢ACB。它有助于很多。 –