當前位置:成語大全網 - 新華字典 - 如何實現IOS分組索引表的效果

如何實現IOS分組索引表的效果

1.新建工程名SearchViewController,File->New->Projectr->SingleView Application->next

2.添加協議和聲明變量

還需要讓類遵循UISearchBarDelegate協議,除了充當表視圖的委托之外還需要讓它充當搜索欄的委托。

view sourceprint?

1.@interface ViewController :UIViewController<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>

2.{

3.UITableView*tableavaieGroup;

4.UISearchBar *search;

5.NSMutableDictionary *names;

6.NSMutableArray *keys;

7.BOOL?isSearching;

8.}

3.添加plist文件,再到ViewDidLoad中初始化視圖

01.- (void)viewDidLoad

02.{

03.//讀取plist文件

04.NSString *path=[[NSBundlemainBundle]pathForResource:@"Property List"ofType:@"plist"];

05.NSDictionary *dictionary=[[NSDictionaryalloc]initWithContentsOfFile:path];

06.//self.names=dictionary;

07.self.allNames=dictionary;

08.//讀取字典中的鍵存儲在數組中

09.//NSArray *array=[[namesallKeys]sortedArrayUsingSelector:@selector(compare:)];

10.//self.myKey=array;

11.[selfresetSearch];

12.[tableViewGroupreloadData];

13.[tableViewGroupsetContentOffset:CGPointMake(0.0, 44.0) animated:NO];

14.[superviewDidLoad];}

4.實現委托方法

從數組中讀取字典中的plist文件有幾個分區

方法獲取壹個可重用單元,如果單元不存在則創建壹個新的單元。然後從對應查詢的數組中獲取對象,將單元的文本設置成控制器標題並返回單元 www.it165.net

view sourceprint?

01.- (UITableViewCell *)tableView:(UITableView *)tableView

02.cellForRowAtIndexPath:(NSIndexPath *)indexPath

03.{

04.staticNSString*DisclosureCellIdentifier = @"DisclosureCellIdentifier";

05.UITableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:DisclosureCellIdentifier];

06.if?(cell == nil)

07.{//創建壹個新的單元

08.cell=[[UITableViewCellalloc] initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:DisclosureCellIdentifier];

09.}

10.//對應查詢數組中獲取的對象,將單元文本設置成控制器標題並返回單元

11.NSUInteger row=[indexPath row];

12.NSString *rowData=[listDataobjectAtIndex:row];

13.cell.textLabel.text=rowData;

14.cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;

15.return?cell;

16.}

5.添加搜索欄委托方法

搜索欄有許多在其委托上調用的方法,當用戶單擊鍵盤上的返回按鈕或搜索鍵時,將調用searchBarBookmarkButtonClicked,此方法從搜索欄獲取搜索短語,並調用我們的搜索方法,這個搜索方法將刪除names中不匹配的名稱和keys中的空分區:

view sourceprint?

1.-(void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar

2.{

3.NSString*searchTerm=[searchBar text];

4.[selfhandleSearchForTerm:searchTerm];

5.}