1

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

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

1 回答 1

2

您可以使用self.view.bounds而不是[mainScreen applicationFrame]. 而且您不必self.view再次分配内存。您可以删除该部分。

于 2013-01-23T03:24:44.473 回答