簡體   English   中英

UITableView的搜索欄作為UIViewController的子視圖

[英]Searchbar for UITableView as subview of UIViewController

在我的應用程序中,我有幾個帶有數組和搜索功能的控制器。 這些數組顯示在表中,搜索工作正常。

但是,我正在嘗試在應用程序的主頁上創建通用搜索。 這將搜索所有數組(我不介意在主頁面視圖控制器中將它們組合為單個數組)。 我嘗試了許多方法來實現這一目標,但仍會遇到困難。 我得到的最遠的是顯示的搜索欄,但是每次我嘗試搜索時它都會崩潰。

我沒有任何代碼可以顯示,因為我沒有任何可用的代碼。 有人能指出我正確的方向嗎? 有教程等嗎?

我用來設置幾個頁面的主要教程是: http : //www.raywenderlich.com/16873/how-to-add-search-into-a-table-view

編輯:我添加了一張圖片來演示我所需要的。

所以我有3個UITableViews,都可以從主UIViewController訪問所有視圖按鈕。 然后,每個UITableView都有一個與之關聯的數組,即TableView Array 2、3和4。

搜索欄2通過TableView Array 2搜索搜索欄3通過TableView Array 3搜索搜索欄4通過TableView Array 4搜索

現在,我在主UIViewController上具有搜索欄1。 我希望此搜索欄搜索所有數組(2、3和4)。 我不介意將所有數組數據組合到UIViewController文件中存在的單個數組中,但是我找不到找到使搜索生效的方法。

圖片: http : //s14.postimg.org/o5z1e5j75/Untitled_1.png

據我了解,您需要一個通用的實現來從3個不同的數組中搜索和顯示內容。 因此,在這種情況下,我通常創建基本控制器類,該類將具有搜索欄和tableView,所有搜索功能以及指向數據源數組的指針。 在瀏覽器中直接輸入,因此可能會出現錯誤。

@interface BaseListController : UIViewController
{
UITableView* _tableView;
UISearchBar* _searchBar;
}
@property NSArray * source;
@poperty (readonly) NSArray * founded;
@end;

然后,您需要確保所有3個數組中的對象都支持特殊的搜索界面:

@protocol SearchedItem <NSObject>
@required
- (NSString *)searchKey;
@end

之后,您的搜索方法將如下所示:

- (void)searchForKey:(NSString *)searchText
{
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"searchKey contains[cd] %@", searchText];
_founded = [self.source filteredArrayUsingPredicate:predicate];

[_tableView reloadData];
}

編輯: 擴展的答案如何以及為什么需要使用@protocol

首先閱讀此書 ,它清楚地說明了如何使用@protocol。
我仍然不知道在這3個數組中將保留什么。 但是可以說,您將保留從NSObject繼承的3個不同類的對象,並將它們稱為ChapterRecipeIngredient 他們每個人都有自己獨特的財產名稱。 為了獨立處理混音,這些類必須具有一些共同點。 常見的問題是單一接口-所有接口都必須符合您定義的@protocol。 這意味着,與該對象的類無關,但是您可以確保它會響應被調用協議的方法。 代碼示例:

// .h file
@interface Chapter : NSObject <SearchedItem>
@property NSString * chapterName;
@property NSArray * recipes;
@end

@interface Recipe : MSObject <SearchedItem>
@property NSString * recipeName;
@property NSArray * ingredients;
@end

@interface Ingredient : NSObject <SearchedItem>
@property NSString * prettyName;
@property NSNumber * enoughCount;
@end

// .m file There you must implement protocol's requied method!
@implementation Chapter
- (NSString *)searchKey{
return self.chapterName;
}
@end

@implementation Recipe 
- (NSString *)searchKey{
return self.recipeName;
}
@end

@implementation Ingredient 
- (NSString *)searchKey{
return self.prettyName;
}
@end

所以現在,在您的cellForRowAtIndexPath:方法中,您可以輕松獲取行標題,而無需知道當前顯示的數據:

id<SearchedItem> item = self.source; //self.founded
cell.titleLabel.text = [item searchKey];

PS,如果您在陣列中存儲簡單的NSString,則不需要任何協議

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM