2013-01-23 176 views
1

我目前正在嘗試以編程方式在帶有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]; 
} 
+0

爲什麼使用'[mainScreen applicationFrame]'?相反,只需嘗試'self.view.bounds'。你不必爲'self.view'再次分配內存。您也可以刪除該行。 – iDev

+0

感謝ACB。它有助於很多。 –

回答

2

可以使用self.view.bounds代替[mainScreen applicationFrame]。而且你不必爲self.view再次分配內存。您可以刪除該部分。

+1

Ooo ...不錯+1(我遇到過這個問題) – TonyMkenu

+0

@TonyMkenu,謝謝Tony .. – iDev