以编程方式创建searchview

时间:2013-01-23 02:22:20

标签: ios

我目前正在尝试使用tableview和searchbar以编程方式在ios中创建searchview。 tableview的工作方式和预期的一样,但是搜索栏在屏幕左侧,只有最后一个像素可见。请告诉我我哪里错了。

- (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];
}

1 个答案:

答案 0 :(得分:2)

您可以使用self.view.bounds代替[mainScreen applicationFrame]。而且你不必再为self.view分配内存。你可以删除那部分。