2015-12-04 55 views
0

我想在UITableView的頂部添加UISearchBar(固定位置!)。UISearchBar - addSubview問題?

CGRect rect = self.headerView.frame; 
CGRect newRect = CGRectMake(0, 
          rect.origin.y + rect.size.height, 
          rect.size.width, 
          CZP_SEARCHBAR_HEIGHT); 

UIView *view = [[UIView alloc] initWithFrame:newRect]; 
view.backgroundColor = [UIColor whiteColor]; 

結果(我有一個白色的矩形上的位置,我想我的吧):

enter image description here

但是,如果我想子視圖添加到我看來,搜索欄上出現的tableview的第一小區(下面我的觀點!)

[view addSubview:searchBar]; 

enter image description here

回答

0

這是一種方法。它看起來像你試圖在代碼而不是故事板,所以這是一個代碼示例。它看起來像你在做一個彈出窗口,我把一個快速項目作爲一個使用彈出窗口的例子,它看起來不像你的,但它足夠接近你的位置去我想。

首先,這裏是代碼示例,它來自包含標題,搜索欄和tableview的視圖控制器。

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    // get the desired size for this popover and setup our header height 
    CGSize viewSize  = self.preferredContentSize; // could also be self.view.bounds.size depending on where you're using it 
    CGFloat headerHeight = 44.0; 

    // setup our desired frames 
    CGRect headerFrame   = CGRectMake(0, 0, viewSize.width, headerHeight); 
    CGRect searchContainerFrame = CGRectMake(0, headerHeight, viewSize.width, headerHeight); 

    // for this frame I'm simply centering it, there's better ways to do it but this is an example 
    CGRect searchBarFrame  = CGRectMake(5, 5, searchContainerFrame.size.width - 10, searchContainerFrame.size.height - 10); 

    // set our tableview frame to be positioned below our header and search container frame 
    CGRect tableviewFrame  = CGRectMake(0, headerHeight *2, viewSize.width, viewSize.height - (headerHeight * 2)); 

    // create our header view and set it's background color 
    UIView *headerView = [[UIView alloc] initWithFrame:headerFrame]; 
    headerView.backgroundColor = [UIColor orangeColor]; 

    // create our container view to hold the search bar (not needed really, but if you want it contained in a view here's how) 
    UIView *searchContainer = [[UIView alloc] initWithFrame:searchContainerFrame]; 
    searchContainer.backgroundColor = [UIColor greenColor]; 

    // instantiate our search bar 
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:searchBarFrame]; 

    // add the search bar to the container view 
    [searchContainer addSubview:searchBar]; 

    // create our tableview and position it below our header and search containers 
    UITableView *tableview = [[UITableView alloc] initWithFrame:tableviewFrame]; 
    tableview.backgroundColor = [UIColor blueColor]; 

    [self.view addSubview:headerView]; 
    [self.view addSubview:searchContainer]; 
    [self.view addSubview:tableview]; 
} 

這段代碼給了我一個橙色標題,綠色/灰色搜索欄和下面的tableview的popover。

enter image description here

編輯:如果您有興趣通過,我曾經把這個共同的項目文件中查找,您可以下載它關閉的github here