2016-01-05 43 views
0

我嘗試使用下面的代碼放置在導航欄搜索欄:將搜索欄編程

UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(-5.0, 0.0, 320.0, 44.0)]; 
    searchBar.autoresizingMask = UIViewAutoresizingFlexibleWidth; 
    UIView *searchBarView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 310.0, 44.0)]; 
    searchBarView.autoresizingMask = 0; 
    searchBar.delegate = self; 
    [searchBarView addSubview:searchBar]; 
    self.navigationItem.titleView = searchBarView; 

它確實放置在導航欄的搜索欄,但不包括按鈕在任何一方。它也沒有取消選項。

enter image description here

我寧願它看起來像這樣:

enter image description here

任何人都可以建議如何調整上面的代碼來做到這一點?

在此先感謝您的任何建議。

+0

你想達到的效果,在視覺上看起來更像是'UISearchController'(或'UISearchDisplayController'之前的iOS 8)在用戶點擊一些模擬搜索欄或其他UI元素之後呈現。請參閱[Apple的示例代碼](https://developer.apple.com/library/ios/samplecode/TableSearch_UISearchController/Introduction/Intro.html)。無論如何,我很想看看別人在幹什麼。 –

+0

蘋果的樣品使用ios9。是否從7.0開始將搜索欄放置在導航欄中? – user1904273

+0

我相信事情沒有改變,因爲你可以把它放到導航欄中,從iOS 7開始。我說的是,你試圖實現的可能的解決方案可能是在導航欄中放置自定義的'UITextField',當用戶點擊它時,會顯示一個搜索控制器。 –

回答

0

在我的一個項目,我沒有使用下面的代碼同樣希望它會幫助你:

-(void)addSearchBar{ 
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(35, -10, 285, 64)]; 
    self.navigationItem.rightBarButtonItems=nil; 

    [self.searchBar setShowsCancelButton:YES]; 
    for (id subView in ((UIView *)[self.searchBar.subviews objectAtIndex:0]).subviews) { 
     NSLog(@"subView====%@", subView); 
     if ([subView isKindOfClass:[UITextField class]]) { 
      UITextField *textField = subView; 
      textField.keyboardAppearance = UIKeyboardAppearanceAlert; 
      break; 
     } 
     if([subView isKindOfClass:[UIButton class]]){ 

      UIButton* cancelBtn = (UIButton*)subView; 
      cancelBtn.frame=CGRectMake(cancelBtn.frame.origin.x, cancelBtn.frame.origin.x, 30, 30); 
      [cancelBtn setTitle:@"" forState:UIControlStateNormal]; 
      [cancelBtn setImage:[UIImage imageNamed:@"btn_cancel_h.png"] forState:UIControlStateNormal]; 
      [cancelBtn setEnabled:YES]; 
     } 
    } 

    [[UIBarButtonItem appearanceWhenContainedIn: [UISearchBar class], nil] setTintColor:[UIColor whiteColor]]; 

      self.searchBar.delegate=self; 
    [self.navigationController.navigationBar addSubview:self.searchBar]; 
}