国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

從零開始學(xué)ios開發(fā)(十三):TableViews(下)GroupedandIndexedSections

2019-11-14 20:19:54
字體:
供稿:網(wǎng)友

在前面2篇關(guān)于Table View的介紹中,我們使用的Style都是Plain,沒有分組,沒有index,這次學(xué)習(xí)的Table View和iphone中的通訊錄很像,有一個(gè)個(gè)以字符為分割的組,最右邊有一列小字符作為index,最頂端有一個(gè)搜索欄可以進(jìn)行搜索,好了,下面開始這次的學(xué)習(xí)。

1)創(chuàng)建一個(gè)新的項(xiàng)目,template選擇Single View application,命名為Sections

2)添加Table View,連接delegate和data source到File's Owner
選中BIDViewController.xib文件,從Object Library中拖一個(gè)Table View到view上,然后選中view中的table view,打開Connections Inspector,拖動(dòng)dataSource和delegate右邊的小圓圈到File's Owner上

3)改變Table View style
還是選中view中的table view,然后選擇Attributes inspector,將Style改成“Grouped”

可以看到,table view的樣子發(fā)生了改變,展現(xiàn)的形式和iphone中的Setting有點(diǎn)類似,一塊一塊的,這樣的table view我們可以叫它Grouped table(之前2篇中所呈現(xiàn)的table view的樣式我們稱之為Plained table,如果在Plained table的右邊加一列索引,我們就稱之為Indexed table,indexed table是我們這張重點(diǎn)要學(xué)習(xí)的)

3)導(dǎo)入數(shù)據(jù)
我們這篇所要學(xué)習(xí)的是數(shù)據(jù)的分組和索引的內(nèi)容,因此我們需要大量的數(shù)據(jù)來做實(shí)驗(yàn),下載下面的文件,然后拖入到項(xiàng)目中,放置在Sections文件夾下
sortednames.plist.zip

選中sortednames.plist,在右邊可以看到文件的內(nèi)容,文件的格式應(yīng)該很熟悉了,我們已經(jīng)多次使用過,sortednames.plist以26個(gè)英文字母為key進(jìn)行分組,各組中的單詞都是以該組的key開頭的。

4)寫代碼
打開BIDViewController.h,添加如下代碼

復(fù)制代碼
#import <UIKit/UIKit.h>@interface BIDViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>@PRoperty (strong, nonatomic) NSDictionary *names;@property (strong, nonatomic) NSArray *keys;@end
復(fù)制代碼

NSDictionary用于存放sortednames.plist中的數(shù)據(jù),用key來對(duì)應(yīng),NSArray用來存放key

打開BIDViewController.m,添加如下代碼

復(fù)制代碼
#import "BIDViewController.h"@implementation BIDViewController@synthesize names;@synthesize keys;......#pragma mark - View lifecycle- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    NSString *path = [[NSBundle mainBundle] pathForResource:@"sortednames" ofType:@"plist"];    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];    self.names = dict;        NSArray *array = [[names allKeys] sortedArrayUsingSelector:@selector(compare:)];    self.keys = array;}- (void)viewDidUnload{    [super viewDidUnload];    // Release any retained subviews of the main view.    // e.g. self.myOutlet = nil;    self.names = nil;    self.keys = nil;}
復(fù)制代碼

上面的code現(xiàn)在讀起來應(yīng)該很容易了,唯一可以稍微解釋一下的就是在viewDidLoad中,使用NSBundle來找到sortednames.plist文件,NSDictionary使用initWithContentsOfFile的方法來讀取數(shù)據(jù)。其他的應(yīng)該不用解釋了。下面繼續(xù)在BIDViewController.m中添加代碼

復(fù)制代碼
#pragma mark -#pragma mark Table View Data Source Methods- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {    return [self.keys count];}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    NSString *key = [keys objectAtIndex:section];    NSArray *nameSection = [names objectForKey:key];    return [nameSection count];}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    NSUInteger section = [indexPath section];    NSUInteger row = [indexPath row];        NSString *key = [keys objectAtIndex:section];    NSArray *nameSection = [names objectForKey:key];        static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];    if(cell == nil) {        cell = [[UITableViewCell alloc]                initWithStyle:UITableViewCellStyleDefault                reuseIdentifier:SectionsTableIdentifier];    }        cell.textLabel.text = [nameSection objectAtIndex:row];    return cell;}- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {    NSString *key = [keys objectAtIndex:section];    return key;}
復(fù)制代碼

這里多了2個(gè)新的方法,解釋如下:
numberOfSectionsInTableView:tableView,這個(gè)方法是返回table view中有多少個(gè)section(group)的,因?yàn)橹暗?篇中section只有一個(gè),因此也就無需這個(gè)方法來返回section的數(shù)量了
tableView:titleForHeaderInSection,這個(gè)方法用來設(shè)置每個(gè)section的title的文字
其他的2個(gè)方法都很熟悉,一個(gè)用來返回每個(gè)section中row的數(shù)量,另一個(gè)用來創(chuàng)建UITableViewCell。
一般來說,table view都是分section的,很少有單一的section的情況,所以在這里每次都要先確定在那個(gè)section中,然后在進(jìn)行針對(duì)cell的操作,上面的code還是很直觀的,應(yīng)該很容易理解。

5)編譯運(yùn)行
編譯運(yùn)行程序,效果如下

每個(gè)section一個(gè)group,每個(gè)section上都有自己的title。如果你將剛才我們?cè)O(shè)置的table view的style改成Plain,在此運(yùn)行,效果會(huì)變成一下的樣子


這個(gè)就是Plain和Grouped的區(qū)別

6)添加Index
上面雖然已經(jīng)實(shí)現(xiàn)的table view,但是用起來還是非常的不方便,例如我們想尋找Z開頭的名字,我們需要花半天時(shí)間,從A一直滑動(dòng)到Z,這樣子手是會(huì)抽筋的,因此,我們需要一個(gè)index,能夠幫我們進(jìn)行快速定位(根據(jù)key值進(jìn)行索引),在BIDViewController.m中,添加如下代碼

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {    return keys;}

sectionIndexTitlesForTableView用于設(shè)置index,它返回index的集合,在這個(gè)例子中,我們的keys是26個(gè)英文字母,我們把這個(gè)作為index,在index中,每一個(gè)字母和一個(gè)section對(duì)應(yīng),第1個(gè)字母對(duì)應(yīng)第一個(gè)section,第2個(gè)字母對(duì)應(yīng)第二個(gè)section,以此類推。是不是比想象的要簡單的多?編譯運(yùn)行程序,table view的右邊出現(xiàn)一列index,選中index中的“Z”,我們可以快速定位到Z對(duì)應(yīng)的section

現(xiàn)在我們可以很方便的定位到需要的section,然后在該section下尋找相關(guān)的name,但是還不是最最方便,很多情況下,我們需要一個(gè)搜索功能,搜索那些包含特定字母的name,這個(gè)可以更快的尋找到我們需要的name,下面我們就為實(shí)現(xiàn)table view的搜素功能。

7)實(shí)現(xiàn)搜索欄(Search Bar)
我們先添加一些文件和代碼,為等會(huì)添加search bar做一些準(zhǔn)備,選中Project navigator中的Sections文件,然后command+N,添加一個(gè)新的文件。在彈出的對(duì)話框中,左邊選擇Cocoa Touch,右邊選擇Objective-C category,然后點(diǎn)擊Next

在下一個(gè)界面中設(shè)置Category和Category on如下,單擊Next

點(diǎn)擊Create,完成文件創(chuàng)建

如果你學(xué)過Objective-C,那么你一定知道什么是Category,如果你對(duì)Objective-C不熟悉,那你肯定會(huì)有疑問,為什么文件名有些詭異(文件名的中間有個(gè)加號(hào)),這個(gè)是Objective-C中獨(dú)有的一種特性、語法現(xiàn)象叫做“Category”,就是為一個(gè)已有的類添加一個(gè)方法而不需要生成其子類,簡單的理解就是在特定的情況下,單獨(dú)為已存在的類添加一個(gè)方法,從上面的名叫命名可以看出NSDictionary+MutableDeepCopy,NSDictionary是已有的類,MutableDeepCopy是為已有的類添加方法,好吧,基本原理就是這些,如果還是有疑惑,那就google、百度一下吧,很快就會(huì)找到答案的。

打開NSDictionary+MutableDeepCopy.h,添加如下代碼

#import <Foundation/Foundation.h>@interface NSDictionary (MutableDeepCopy)- (NSMutableDictionary *)mutableDeepCopy;@end

這里為NSDictionary添加了一個(gè)mutableDeepCopy的方法,再打開NSDictionary+MutableDeepCopy.m,添加如下代碼

復(fù)制代碼
@implementation NSDictionary (MutableDeepCopy)- (NSMutableDictionary *)mutableDeepCopy {    NSMutableDictionary *returnDict = [[NSMutableDictionary alloc] initWithCapacity:[self count]];    NSArray *keys = [self allKeys];    for(id key in keys) {        id oneValue = [self valueForKey:key];        id oneCopy = nil;                if([oneValue respondsToSelector:@selector(mutableDeepCopy)])            oneCopy = [oneValue mutableDeepCopy];        else if([oneValue respondsToSelector:@selector(mutableCopy)])            oneCopy = [oneValue mutableCopy];        if (oneCopy == nil)            oneCopy = [oneValue copy];        [returnDict setValue:oneCopy forKey:key];                }    return returnDict;}@end
復(fù)制代碼

這里是對(duì)mutableDeepCopy方法進(jìn)行實(shí)現(xiàn),從字面意思就可以清楚的知道是對(duì)一個(gè)NSDictionary對(duì)象進(jìn)行深拷貝(這個(gè)概念在C#中也有,是類似的東西),實(shí)現(xiàn)深拷貝的原因再后面會(huì)說到。

打開BIDViewController.h,添加如下代碼

復(fù)制代碼
#import <UIKit/UIKit.h>@interface BIDViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>@property (strong, nonatomic) NSDictionary *names;@property (strong, nonatomic) NSArray *keys;@property (strong, nonatomic) NSMutableDictionary *names;@property (strong, nonatomic) NSMutableArray *keys;@property (strong, nonatomic) IBOutlet UITableView *table;@property (strong, nonatomic) IBOutlet UISearchBar *search;@property (strong, nonatomic) NSDictionary *allNames;- (void)resetSearch;- (void)handleSearchForTeam:(NSString *)searchTerm;@end
復(fù)制代碼

引入U(xiǎn)ISearchBarDelegate,之后的searchbar需要這個(gè)協(xié)議來實(shí)現(xiàn)方法
刪除之前聲明的names和keys,替換成mutable(可修改的)的Dictionary和Array,因?yàn)橹笥袑?duì)names和keys的刪除操作,NSDictionary和NSArray都是immutable(不可修改的),我們的搜索結(jié)果是比較所有的names,把不符合的names從dictionary中刪除,把不符合的key從array中刪除,所以dictionary和array必須是可修改的,因此我們聲明NSMutableDictionary和NSMutableArray
聲明2個(gè)outlet分別控制table view和searchbar
聲明一個(gè)NSDictionary,用于存放完整的names

8)添加Search Bar
選中BIDViewController.xib,在Object library中找到Search Bar,把Search Bar放在view的最頂端,searchbar會(huì)自動(dòng)拉伸以適應(yīng)屏幕的寬度,table view會(huì)自動(dòng)空出頂部searchbar的位置

選中searchbar,打開attributes inspector,找到Options下的“Shows Cancel Button”,這樣一個(gè)Cancel按鈕會(huì)出現(xiàn)在search欄的右邊

ok,此時(shí)我們先build一下我們的project,當(dāng)然會(huì)有很多警告出現(xiàn),我們暫時(shí)無視,然后運(yùn)行程序,一個(gè)bug出現(xiàn)了

最右邊的index和searchbar上的Cancel按鈕重疊了,好吧,我們必須解決這個(gè)問題,解決的方法可以說比較笨拙但也可以認(rèn)為比較巧妙,大致的方法是在searchbar下面放一個(gè)墊背的View控件,然后這個(gè)墊背的View控件上放2個(gè)其他的控件,一個(gè)是searchbar,另一個(gè)是navigation bar。View控件的作用有2個(gè),一是占據(jù)table view上的空間,當(dāng)往table view上拖一個(gè)View控件時(shí),table view會(huì)自動(dòng)讓出頂部的hearder section;View控件的第二個(gè)作用是它可以容納其他的控件,可以在它上面放置searchbar和navigation bar(為什么要使用navigation bar,這個(gè)后面會(huì)解釋)。

好了,下面我們進(jìn)行具體的操作,先將searchbar從table view上面刪除,然后在Object library中找到View控件

將View控件拖到table view的頂部,table view上會(huì)有一個(gè)藍(lán)色的小框框出現(xiàn)(table view的hearder section),將View放置在其中

再從Object library中拖一個(gè)Search Bar到View上,調(diào)整Search Bar的寬度到295(選中searchbar的情況下,打開size inspector,設(shè)置Width=295)

最后一步是拖一個(gè)navigation bar,在Object library中找到Navigation Bar

默認(rèn)的Navigation Bar會(huì)充滿整個(gè)View控件

先雙擊navigation bar上的Title,然后將Title刪除,我們這里不需要使用到文字內(nèi)容,然后調(diào)整navigation bar的寬度,在dock中選中“Navigation Bar”

拖動(dòng)左邊的點(diǎn),使其的寬度縮小為25px,這樣navigation bar的寬度正好填充了剛才search bar空出的寬度,而且search bar從見天日了。

選中searchbar,打開attributes inspector,在Options下的選中“Shows Cancel Button”,在Placeholder中填入“Search”,再編譯運(yùn)行一次,最終的效果如下

怎么樣,很完美吧,完全看不出來是2個(gè)控件,這里可以解釋一下選擇Navigation Bar的原因了,因?yàn)镹avigation Bar刪除title后,其背景顏色和Search Bar是一樣的,這樣我們就可以使2個(gè)控件看上去“合二為一”,最終達(dá)到我們需要的效果。但是為什么不直接拖一個(gè)Navigation Bar呢?因?yàn)镹avigation Bar無法讓table view為其留出頂部的header section,所有需要View控件來代勞。

9)連接
選中File's Owner,control-drag到table view,在彈出的框中選擇“table”

同樣的方法,control-drag到search bar,選擇“search”

這樣就將剛才在BIDViewController.h中定義的2個(gè)outlet分類連接到了它們負(fù)責(zé)的對(duì)象上面。

選中search bar,打開connections inspector,將delegate拖動(dòng)到File's Owner上,我們?cè)贐IDViewController.h中引入了UISearchBarDelegate,因此就讓這個(gè)search bar到BIDViewController中去尋找方法。

10)寫代碼
打開BIDViewController.m,添加如下代碼

復(fù)制代碼
#import "BIDViewController.h"#import "NSDictionary+MutableDeepCopy.h"@implementation BIDViewController@synthesize names;@synthesize keys;@synthesize table;@synthesize search;@synthesize allNames;#pragma mark -#pragma mark Custom Methods- (void)resetSearch {    self.names = [self.allNames mutableDeepCopy];    NSMutableArray *keyArray = [[NSMutableArray alloc] init];    [keyArray addObjectsFromArray:[[self.allNames allKeys] sortedArrayUsingSelector:@selector(compare:)]];    self.keys = keyArray;}- (void)handleSearchForTeam:(NSString *)searchTerm {        NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];    [self resetSearch];        for (NSString *key in self.keys) {        NSMutableArray *array = [names valueForKey:key];        NSMutableArray *toRemove = [[NSMutableArray alloc] init];        for (NSString *name in array) {            if ([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound) {                [toRemove addObject:name];            }        }        if ([array count] == [toRemove count]) {            [sectionsToRemove addObject:key];        }                [array removeObjectsInArray:toRemove];    }    [self.keys removeObjectsInArray:sectionsToRemove];    [table reloadData];}
復(fù)制代碼

引入NSDictionary+MutableDeepCopy.h,就可以調(diào)用我們定義的mutableDeepCopy方法了

resetSearch:是一個(gè)SearchBar的delegate,用于初始化搜索內(nèi)容,將完整的names和keys復(fù)制到NSMutableDictionary和NSMutableArray中,之后的搜索就搜索這2個(gè)對(duì)象中的內(nèi)容,可以對(duì)他們進(jìn)行刪除操作。這個(gè)方法會(huì)在點(diǎn)擊searchbar上的Cancel按鈕和當(dāng)搜索的關(guān)鍵詞發(fā)生改變時(shí)進(jìn)行調(diào)用。

handleSearchForTeam:searchTerm:SearchBar的另一個(gè)delegate,根據(jù)搜索詞searchTerm來進(jìn)行搜索

NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init]; //聲明一個(gè)NSMutableArray,用于記錄哪些section可以整個(gè)的被刪除,即某個(gè)index item下的所有name都不符合搜索的要求,這個(gè)index item就可以被刪除了
[self resetSearch]; //初始化搜索對(duì)象,一個(gè)是NSMutableDictionary,另一個(gè)是NSMutableArray
for (NSString *key in self.keys) { //循環(huán)遍歷所有的key
    NSMutableArray *array = [names valueForKey:key]; //根據(jù)key取得對(duì)應(yīng)的name
    NSMutableArray *toRemove = [[NSMutableArray alloc] init]; //初始化一個(gè)NSMutableArray,用于記錄可刪除的name
    for (NSString *name in array) { //循環(huán)遍歷當(dāng)前key下的name
        if ([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound) { //如果當(dāng)前的name中不包含搜索詞searchTerm,那這個(gè)name是可以被刪除的
            [toRemove addObject:name]; //將name添加到toRemove array中
        }
    }
    if ([array count] == [toRemove count]) { //判斷是不是可以刪除的name個(gè)數(shù)和當(dāng)前section(index item)下的name個(gè)數(shù)一樣,一樣的話,真?zhèn)€的section就可以被刪除了
        [sectionsToRemove addObject:key]; //將可以刪除的section添加到array中
    }
    [array removeObjectsInArray:toRemove]; //刪除name
}
[self.keys removeObjectsInArray:sectionsToRemove]; //刪除section
[table reloadData]; //重新載入數(shù)據(jù)

下面繼續(xù)添加code

復(fù)制代碼
- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    NSString *path = [[NSBundle mainBundle] pathForResource:@"sortednames" ofType:@"plist"];    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];    self.names = dict;    self.allNames = dict;        NSArray *array = [[names allKeys] sortedArrayUsingSelector:@selector(compare:)];    self.keys = array;        [self resetSearch];    [table reloadData];    [table setContentOffset:CGPointMake(0.0, 44.0) animated:NO];}- (void)viewDidUnload{    [super viewDidUnload];    // Release any retained subviews of the main view.    // e.g. self.myOutlet = nil;    self.names = nil;    self.keys = nil;    self.table = nil;    self.search = nil;    self.allNames = nil;}
復(fù)制代碼

這里需要解釋的就是[table setContentOffset:CGPointMake(0.0, 44.0) animated:NO];,將table view上移動(dòng)44px,這樣當(dāng)初次載入程序的時(shí)候,搜索欄不會(huì)顯示,只用向下拖動(dòng)table view,searchbar才會(huì)出現(xiàn)。

繼續(xù)添加code

復(fù)制代碼
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {    return [self.keys count];    return ([keys count] > 0) ? [keys count] : 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {    if([keys count] == 0)        return 0;        NSString *key = [keys objectAtIndex:section];    NSArray *nameSection = [names objectForKey:key];    return [nameSection count];}......- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {    if([keys count] == 0)        return nil;        NSString *key = [keys objectAtIndex:section];    return key;}
復(fù)制代碼

增加的幾個(gè)if語句都是用于判斷search結(jié)果的,調(diào)用完handleSearchForTeam:searchTerm后,看還有多少個(gè)key和name

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {    [search resignFirstResponder];    return indexPath;}

table view的delegate方法,當(dāng)點(diǎn)擊table view上的一行是,將彈出的鍵盤隱藏

復(fù)制代碼
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {    NSString *searchTeam = [searchBar text];    [self handleSearchForTeam:searchTeam];}- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchTerm {    if ([searchTerm length] == 0) {        [self resetSearch];        [table reloadData];        return;    }    [self handleSearchForTeam:searchTerm];}- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {    search.text = @"";    [self resetSearch];    [table reloadData];    [searchBar resignFirstResponder];}
復(fù)制代碼

三個(gè)Search Bar的delegate方法
searchBarSearchButtonClicked:searchBar當(dāng)點(diǎn)擊虛擬鍵盤上的search按鈕時(shí),調(diào)用該方法
searchBar:textDidChange:當(dāng)searchBar上的輸入發(fā)生改變時(shí),調(diào)用該方法
searchBarCancelButtonClicked:searchBar當(dāng)點(diǎn)擊searchbar上的Cancel按鈕時(shí),調(diào)用該方法

好了,所有的code添加完畢,編譯運(yùn)行,效果如下

當(dāng)程序啟動(dòng)后,searchbar是看不見的,因?yàn)槲覀儗able view上移了44px,將table view向下拖動(dòng)后,searchbar出現(xiàn)了

點(diǎn)擊search bar的輸入欄,調(diào)出鍵盤,然后我們輸入“ab”,table view總的內(nèi)容會(huì)隨之改變,只顯示含有關(guān)鍵詞“ab”的name,index也會(huì)改變

點(diǎn)擊table view中的一行,鍵盤會(huì)隱藏

11)隱藏index
如果我們希望在搜索的時(shí)候隱藏index,添加下面的code

在BIDViewController.h中添加一個(gè)property

復(fù)制代碼
@interface BIDViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>@property (strong, nonatomic) NSMutableDictionary *names;@property (strong, nonatomic) NSMutableArray *keys;@property (strong, nonatomic) IBOutlet UITableView *table;@property (strong, nonatomic) IBOutlet UISearchBar *search;@property (strong, nonatomic) NSDictionary *allNames;@property (assign, nonatomic) BOOL isSearching;
復(fù)制代碼

注意,這里用的是assign(不好意思,我還沒有弄清楚為什么要用assign,因此無法解釋,了解的同學(xué)們幫忙指導(dǎo)一下,謝謝)

在BIDViewController.m中添加code

復(fù)制代碼
#import "BIDViewController.h"#import "NSDictionary+MutableDeepCopy.h"@implementation BIDViewController@synthesize names;@synthesize keys;@synthesize table;@synthesize search;@synthesize allNames;@synthesize isSearching;......- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {    if(isSearching)        return nil;    return keys;}- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {    [search resignFirstResponder];    isSearching = NO;    search.text = @"";    [table reloadData];    return indexPath;}......- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {    isSearching = NO;    search.text = @"";    [self resetSearch];    [table reloadData];    [searchBar resignFirstResponder];}- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {    isSearching = YES;    [table reloadData];}
復(fù)制代碼

添加了一個(gè)新的Search Bar的delegate:searchBarTextDidBeginEditing,當(dāng)開始鍵入搜索詞的時(shí)候,設(shè)置標(biāo)識(shí)符isSearching為YES,然后重新載入table,當(dāng)重新載入table的時(shí)候,就會(huì)判斷isSearching是否為YES,如果是,就不顯示index。其他的代碼修改應(yīng)該都可以看懂吧,就不解釋了,編譯運(yùn)行程序,點(diǎn)擊搜索欄,index消失了,效果如下

當(dāng)結(jié)束搜索(點(diǎn)擊search bar的Cancel按鈕或者選中table view中的一行),index就會(huì)顯示出來

12)添加index中的放大鏡
現(xiàn)在的index定位,只能定位到某個(gè)section,如果想直接定位到search bar還是不行的,我們需要添加額外的代碼,使其可以定位到search bar,基本思路如下:
添加一個(gè)特殊的值到keys中,然后點(diǎn)擊這個(gè)特別的key,就可以定位到search bar
阻止iOS為這個(gè)特殊的key生成一個(gè)section hearder,其他的keys(A、B、C.....Z)每個(gè)都一個(gè)section header
當(dāng)這個(gè)特殊的key被選中時(shí),定位到search bar

復(fù)制代碼
- (void)resetSearch {    self.names = [self.allNames mutableDeepCopy];    NSMutableArray *keyArray = [[NSMutableArray alloc] init];    [keyArray addObject:UITableViewIndexSearch];    [keyArray addObjectsFromArray:[[self.allNames allKeys] sortedArrayUsingSelector:@selector(compare:)]];    self.keys = keyArray;}......- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {    if([keys count] == 0)        return nil;        NSString *key = [keys objectAtIndex:section];    if (key == UITableViewIndexSearch) {        return nil;    }    return key;}......- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {    NSString *key = [keys objectAtIndex:index];    if(key == UITableViewIndexSearch) {        [tableView setContentOffset:CGPointZero animated:NO];        return NSNotFound;    }    else        return index;}
復(fù)制代碼

resetSearch方法中為key添加了一個(gè)iOS自帶的對(duì)象[keyArray addObject:UITableViewIndexSearch],這個(gè)就是放大鏡。
titleForHeaderInSection中,判斷key是不是UITableViewIndexSearch,如果是,就返回nil,不顯示section header
最后添加了一個(gè)新的delegate,用于定位到search bar

編譯運(yùn)行,放大鏡出現(xiàn)了
點(diǎn)擊放大鏡,就可以定位到search bar了

13)總結(jié)
終于要完結(jié)這篇了,花了好長時(shí)間,內(nèi)容比較多,比較復(fù)雜,不過很實(shí)用,很多app程序都用到這些基礎(chǔ)的東西,其實(shí)也不難,很多方法都是iOS自帶的,我們只需要自己調(diào)用一下即可,總的來說,收獲還是很大的,加油吧!

Sections


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 台安县| 叙永县| 都昌县| 丽水市| 靖远县| 通榆县| 中山市| 德阳市| 汶川县| 左贡县| 清水河县| 衡阳市| 时尚| 久治县| 古浪县| 利川市| 辽宁省| 白河县| 遂平县| 乐亭县| 大渡口区| 肥西县| 桃江县| 武川县| 阳东县| 阳城县| 平阴县| 鲁甸县| 双辽市| 台州市| 修水县| 泰宁县| 兴业县| 昌宁县| 宁乡县| 宜兴市| 怀来县| 汉中市| 石狮市| 宜章县| 余庆县|