2016-10-26 33 views
-1

我添加了一個UISearchBar作爲UIBarButtonItem(正確的一個)。我需要顯示「取消」按鈕,但我無法顯示它。我正在開發的應用程序是用於iPad,並且是用Objective-C編寫的。 爲了與您分享,期望的行爲是在搜索欄獲得焦點時增加搜索欄的寬度(向左+ 50px),因此我必須找到適合此要求的解決方案。 預先感謝您UISearchBar作爲UIBarButtonItem

+0

downvote有什麼好的理由嗎? –

回答

0

UISearchBar應該設置爲導航項目titleView屬性,因此這可能是您遇到的第一個問題。然後,您可以通過showsCancelButton屬性告訴搜索欄顯示其取消按鈕。這應該解決您的問題,不顯示取消按鈕。然後,您可以使用UISearchBarDelegate方法,以便在搜索欄進入/離開焦點時爲其設置動畫效果。

下面的代碼顯示了所有這些行爲。

#import "ViewController.h" 

@interface ViewController() <UISearchBarDelegate> 

@property (strong, nonatomic) UISearchBar *searchBar; 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    self.searchBar = [UISearchBar new]; 
    self.searchBar.delegate = self; 
    self.searchBar.showsCancelButton = YES; 

    self.navigationItem.titleView = self.searchBar; 
} 

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar { 
    [self.searchBar resignFirstResponder]; 
} 

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar { 
    // Animate to new position 
} 

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar { 
    // Animate back to original position 
} 

@end 

PS:這是不可能添加一個UISearchBar實例作爲UIBarButtonItem。它實際上會導致不兼容的指針類型警告和運行時崩潰。這可能是人們降低你的問題的原因。

相關問題