1.創(chuàng)建一個(gè)Navigation—based—Application項(xiàng)目,這樣Interface Builder中會(huì)自動(dòng)生成一個(gè)Table View,然后將Search Bar拖放到表示圖上,以我們要給表示圖添加搜索功能,不要忘記將Search Bar的delegate連接到File‘s Owner項(xiàng),然后將Search Bar與searchBar變量連接。
2.在Resources文件夾下創(chuàng)建一個(gè)Movies.plist文件,然后為該文件添加一些數(shù)據(jù),如下圖:
3.在.h頭文件添加如下內(nèi)容:
[cpp] view plaincopyprint?
#import?<UIKit/UIKit.h> ???? ?? @interface?MyTableView?:?UITableViewController?<UISearchBarDelegate>{?? ????NSDictionary?*movieTitles;?? ????NSArray?*years;?? ?????? ????IBOutlet?UISearchBar?*searchBar;?? ?????? ????BOOL ?isSearchOn;?? ????BOOL ?canSelectRow;?? ?????? ?????? ????NSMutableArray?*listOfMovies;?? ????NSMutableArray?*searchResult;?? }?? @property(nonatomic,retain)?NSDictionary?*movieTitles;?? @property(nonatomic,retain)NSArray?*years;?? @property(nonatomic,retain)UISearchBar?*searchBar;?? ?? -(void )donSearching:(id)sender;?? -(void )searchMoviesTableView;?? @end??
#import <UIKit/UIKit.h>@interface MyTableView : UITableViewController <UISearchBarDelegate>{NSDictionary *movieTitles;NSArray *years;IBOutlet UISearchBar *searchBar;BOOL isSearchOn;BOOL canSelectRow;//下面兩個(gè)是搜索用到的兩個(gè)變量NSMutableArray *listOfMovies;NSMutableArray *searchResult;
}
@property(nonatomic,retain) NSDictionary *movieTitles;
@property(nonatomic,retain)NSArray *years;
@property(nonatomic,retain)UISearchBar *searchBar;-(void)donSearching:(id)sender;
-(void)searchMoviesTableView;
@end
4.當(dāng)加載View窗口時(shí),首先定位屬性列表并把這個(gè)列表加載到listOfMovies中,然后將所有的年份提取到y(tǒng)ears中,然后添加搜索條并初始化搜索條用到的數(shù)據(jù):
[cpp] view plaincopyprint?
?? -?(void )viewDidLoad?? {?? ???NSString?*path?=?[[NSBundle?mainBundle]pathForResource:@"Movies" ?ofType:@"plist" ];?? ????NSDictionary?*dic?=?[[NSDictionary?alloc]initWithContentsOfFile:path];?? ????self.movieTitles?=?dic;?? ????[dic?release];?? ?????? ????NSArray?*array?=?[[self.movieTitles?allKeys]sortedArrayUsingSelector:@selector(compare:)];?? ????self.years?=?array;?? ?????? ?????? ????self.tableView.tableHeaderView?=?searchBar;?? ????self.searchBar.autocorrectionType?=?UITextAutocorrectionTypeYes;?? ?????? ?????? ????listOfMovies?=?[[NSMutableArray?alloc]init];?? ????for ?(NSString?*year?in?years)?{?? ????????NSArray?*movies?=?[movieTitles?objectForKey:year];?? ????????for (NSString?*title?in?movies){?? ????????????[listOfMovies?addObject:title];?? ????????}?? ????}?? ?? ????searchResult?=?[[NSMutableArray?alloc]init];?? ?????? ????isSearchOn?=?NO;?? ????canSelectRow?=?YES;?? ????[super?viewDidLoad];?? ?? }??
//讀取Movies.plist文件的內(nèi)容到變量里面
- (void)viewDidLoad
{NSString *path = [[NSBundle mainBundle]pathForResource:@"Movies" ofType:@"plist"];NSDictionary *dic = [[NSDictionary alloc]initWithContentsOfFile:path];self.movieTitles = dic;[dic release];NSArray *array = [[self.movieTitles allKeys]sortedArrayUsingSelector:@selector(compare:)];self.years = array;//下面兩句是添加搜索條self.tableView.tableHeaderView = searchBar;self.searchBar.autocorrectionType = UITextAutocorrectionTypeYes;//初始化listofmovieslistOfMovies = [[NSMutableArray alloc]init];for (NSString *year in years) {NSArray *movies = [movieTitles objectForKey:year];for(NSString *title in movies){[listOfMovies addObject:title];}}searchResult = [[NSMutableArray alloc]init];isSearchOn = NO;canSelectRow = YES;[super viewDidLoad];}
5.在自動(dòng)生成的方法numberOfSectionsInTableView中添加如下代碼,表示告訴表示圖一共分多少節(jié):
[cpp] view plaincopyprint?
-?(NSInteger)numberOfSectionsInTableView:(UITableView?*)tableView?? {?? ????if ?(isSearchOn)?{?? ????????return ?1;?? ????}?? ??else ?? ????return ?[self.years?count];?? }??
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{if (isSearchOn) {return 1;//如果正在搜索就只有一個(gè)section}elsereturn [self.years count];
}
6.在自動(dòng)生成的方法tableView:numberOfRowsInSection:中添加如下代碼,表示告訴表視圖每一節(jié)顯示多少行:
[cpp] view plaincopyprint?
-?(NSInteger)tableView:(UITableView?*)tableView?numberOfRowsInSection:(NSInteger)section?? {?? ?? ????if ?(isSearchOn)?{?? ????????return ?[searchResult?count];?? ????}else {?? ?????? ????NSString?*year?=?[self.years?objectAtIndex:section];?? ????NSArray?*movieSection?=?[self.movieTitles?objectForKey:year];?? ????return ?[movieSection?count];?? ????}?? }??
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{if (isSearchOn) {return [searchResult count];}else{// Return the number of rows in the section.NSString *year = [self.years objectAtIndex:section];NSArray *movieSection = [self.movieTitles objectForKey:year];return [movieSection count];}
}
7.在自動(dòng)生成的方法tableView:cellForRowAtIndexPath:中添加如下代碼,為每一行設(shè)值:
[cpp] view plaincopyprint?
-?(UITableViewCell?*)tableView:(UITableView?*)tableView?cellForRowAtIndexPath:(NSIndexPath?*)indexPath?? {?? ????static ?NSString?*CellIdentifier?=?@"Cell" ;?? ?????? ????UITableViewCell?*cell?=?[tableView?dequeueReusableCellWithIdentifier:CellIdentifier];?? ????if ?(cell?==?nil)?{?? ????????cell?=?[[[UITableViewCell?alloc]?initWithStyle:UITableViewCellStyleDefault?reuseIdentifier:CellIdentifier]?autorelease];?? ????}?? ?????? ????if ?(isSearchOn)?{?? ????????NSString?*cellValue?=?[searchResult?objectAtIndex:indexPath.row];?? ????????cell.textLabel.text?=?cellValue;?? ????}else {?? ????NSString?*year?=?[self.years?objectAtIndex:[indexPath?section]];?? ????NSArray?*movieSection?=?[self.movieTitles?objectForKey:year];?? ????cell.textLabel.text?=?[movieSection?objectAtIndex:[indexPath?row]];?? ?????????? ????????cell.accessoryType?=?UITableViewCellAccessoryDetailDisclosureButton;?? ????}?? ?????? ?????? ????UIImage?*image?=?[UIImage?imageNamed:@"apple.jpeg" ];?? ????cell.imageView.image?=?image;?? ?????? ????return ?cell;?? }??
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{static NSString *CellIdentifier = @"Cell";UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];if (cell == nil) {cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];}if (isSearchOn) {NSString *cellValue = [searchResult objectAtIndex:indexPath.row];cell.textLabel.text = cellValue;}else{NSString *year = [self.years objectAtIndex:[indexPath section]];//得到當(dāng)前行所在的sectionNSArray *movieSection = [self.movieTitles objectForKey:year];cell.textLabel.text = [movieSection objectAtIndex:[indexPath row]];cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;}//為每一行添加圖片UIImage *image = [UIImage imageNamed:@"apple.jpeg"];cell.imageView.image = image;return cell;
}
8.實(shí)現(xiàn)tableView:titleForHeaderInSection:方法,將得到的年份作為每一節(jié)的Header:
[cpp] view plaincopyprint?
?? -(NSString?*)tableView:(UITableView?*)tableView?titleForHeaderInSection:(NSInteger)section{?? ????NSString?*year?=?[self.years?objectAtIndex:section];?? ????if ?(isSearchOn)?{?? ????????return ?nil;?? ????}?? ????else {?? ????return ?year;?? ????}?? ????}??
//設(shè)置每個(gè)section的標(biāo)題
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{NSString *year = [self.years objectAtIndex:section];if (isSearchOn) {return nil;}else{return year;}}
9.為表格添加索引,只需要實(shí)現(xiàn)sectionIndexTitlesForTableView:方法,該方法返回每一節(jié)的Header數(shù)組:
[cpp] view plaincopyprint?
?? -(NSArray?*)sectionIndexTitlesForTableView:(UITableView?*)tableView{?? ????if ?(isSearchOn)??? ????????return ?nil;?? ????else ?? ????return ?years;?? }??
//添加索引
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{if (isSearchOn) return nil;elsereturn years;
}
10.當(dāng)用戶點(diǎn)擊搜索欄會(huì)促發(fā)searchBarTextDidBeginEditing:事件(UISearchBarDelegate協(xié)議中定義的一個(gè)方法,我們?cè)?h頭文件中實(shí)現(xiàn)了這個(gè)協(xié)議),在該方法中,向屏幕右上角添加一個(gè)Done按鈕,當(dāng)用戶點(diǎn)擊Done按鈕時(shí)會(huì)調(diào)用doneSearching方法:
[cpp] view plaincopyprint?
?? -(void )searchBarTextDidBeginEditing:(UISearchBar?*)searchBar{?? ????isSearchOn?=?YES;?? ????canSelectRow?=?NO;?? ????self.tableView.scrollEnabled?=?NO;?? ?????? ????self.navigationItem.rightBarButtonItem?=?[[[UIBarButtonItem?alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone?target:self?action:@selector(donSearching:)]autorelease];?? }??
//搜索筐得到焦點(diǎn)后
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{isSearchOn = YES;canSelectRow = NO;self.tableView.scrollEnabled = NO;//添加down按鈕及其點(diǎn)擊方法self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(donSearching:)]autorelease];
}11.doneSearching方法使得搜索欄移除了First Responder狀態(tài),因而會(huì)隱藏鍵盤,同時(shí),通過調(diào)用表視圖的reloadData方法重新加載表視圖:
[cpp] view plaincopyprint?
?? -(void )donSearching:(id)sender{?? ????isSearchOn?=?NO;?? ????canSelectRow?=?YES;?? ????self.tableView.scrollEnabled?=?YES;?? ????self.navigationItem.rightBarButtonItem?=?nil;?? ?????? ????[searchBar?resignFirstResponder];?? ?????? ????[self.tableView?reloadData];?? }??
//點(diǎn)擊down按鈕后
-(void)donSearching:(id)sender{isSearchOn = NO;canSelectRow = YES;self.tableView.scrollEnabled = YES;self.navigationItem.rightBarButtonItem = nil;[searchBar resignFirstResponder];[self.tableView reloadData];
}
12.當(dāng)用戶在搜索欄中輸入時(shí),輸入的每個(gè)字符都會(huì)觸發(fā)searchBar:textDidChange:事件,只要搜索欄中有一個(gè)字符,就會(huì)調(diào)用searchMoviesTableView方法:
[cpp] view plaincopyprint?
?? -(void )?searchBar:(UISearchBar?*)searchBar?textDidChange:(NSString?*)searchText{?? ????if ?([searchText?length]>0)?{?? ????????isSearchOn?=?YES;?? ????????canSelectRow?=?YES;?? ????????self.tableView.scrollEnabled?=?YES;?? ????????[self?searchMoviesTableView];?? ????}?? ????else {?? ????????isSearchOn?=?NO;?? ????????canSelectRow?=?NO;?? ????????self.tableView.scrollEnabled?=?NO;?? ????}?? ????[self.tableView?reloadData];?? }??
//搜索筐里面的文字改變后
-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{if ([searchText length]>0) {isSearchOn = YES;canSelectRow = YES;self.tableView.scrollEnabled = YES;[self searchMoviesTableView];//調(diào)用搜索方法}else{isSearchOn = NO;canSelectRow = NO;self.tableView.scrollEnabled = NO;}[self.tableView reloadData];
}
13.searchMoviesTableView方法會(huì)搜索listOfMovies數(shù)組,通過NSString類的rangeOfString:options:方法,使用特定的字符串對(duì)每個(gè)名稱進(jìn)行搜索,返回的結(jié)果是一個(gè)nsRange對(duì)象,如果長度大于0就表示有一個(gè)匹配結(jié)果,將它添加到searchResult書組中:
[cpp] view plaincopyprint?
?? -(void )searchMoviesTableView{?? ????[searchResult?removeAllObjects];?? ????for ?(NSString?*str?in?listOfMovies)?{?? ????????NSRange?titleResultsRange?=?[str?rangeOfString:searchBar.text?options:NSCaseInsensitiveSearch];?? ????????if ?(titleResultsRange.length?>?0)?{?? ????????????[searchResult?addObject:str];?? ????????}?? ????}?? }??
//自定義的搜索方法,得到搜索結(jié)果
-(void)searchMoviesTableView{[searchResult removeAllObjects];for (NSString *str in listOfMovies) {NSRange titleResultsRange = [str rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];if (titleResultsRange.length > 0) {[searchResult addObject:str];}}
}
14.當(dāng)用戶點(diǎn)擊鍵盤上的Search按鈕時(shí),就會(huì)調(diào)用如下方法:
[cpp] view plaincopyprint?
-(void )?searchBarSearchButtonClicked:(UISearchBar?*)searchBar{?? ????[self?searchMoviesTableView];?? }??
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar{[self searchMoviesTableView];
}
15.新建一個(gè)新的文件,該文件在后面定義,點(diǎn)擊表格的某一行后就會(huì)調(diào)轉(zhuǎn)到該頁面去并將點(diǎn)擊的那一樣的名稱傳過去,要想做到這一點(diǎn)必須實(shí)現(xiàn)如下方法:
[cpp] view plaincopyprint?
?? -?(void )tableView:(UITableView?*)tableView?didSelectRowAtIndexPath:(NSIndexPath?*)indexPath?? {?? ????MyTableViewOneMessage?*mytm?=?[[MyTableViewOneMessage?alloc]initWithNibName:@"MyTableViewOneMessage" ?bundle:nil];?? ?????? ????NSString?*year?=?[self.years?objectAtIndex:[indexPath?section]];?? ????NSArray?*movieSection?=?[self.movieTitles?objectForKey:year];?? ????NSString?*movieTitle?=?[movieSection?objectAtIndex:[indexPath?row]];?? ????NSString?*message?=?[[NSString?alloc]initWithFormat:@"%@" ,movieTitle];?? ????mytm.message?=?message;?? ????[self.navigationController?pushViewController:mytm?animated:YES];?? ????[mytm?release];?? }??
//點(diǎn)擊table某一行跳轉(zhuǎn)頁面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{MyTableViewOneMessage *mytm = [[MyTableViewOneMessage alloc]initWithNibName:@"MyTableViewOneMessage" bundle:nil];NSString *year = [self.years objectAtIndex:[indexPath section]];NSArray *movieSection = [self.movieTitles objectForKey:year];NSString *movieTitle = [movieSection objectAtIndex:[indexPath row]];NSString *message = [[NSString alloc]initWithFormat:@"%@",movieTitle];mytm.message = message;[self.navigationController pushViewController:mytm animated:YES];[mytm release];
}
16.新添加的頁面很簡單,主要用來測試表格的點(diǎn)擊事件,導(dǎo)航然后顯示傳過來的字符串:
Interface Builder中添加兩個(gè)lable,具體的就不詳細(xì)了,很簡單的,下面是這個(gè)界面的.h和.m文件:
[cpp] view plaincopyprint?
#import?<UIKit/UIKit.h> ???? ?? @interface?MyTableViewOneMessage?:?UIViewController?{?? ????IBOutlet?UILabel?*mylable;?? ????NSString?*message;?? }?? ?? @property(nonatomic,retain)UILabel?*mylable;?? @property(nonatomic,retain)NSString?*message;?? ?? @end??
#import <UIKit/UIKit.h>@interface MyTableViewOneMessage : UIViewController {IBOutlet UILabel *mylable;NSString *message;
}@property(nonatomic,retain)UILabel *mylable;
@property(nonatomic,retain)NSString *message;@end
[cpp] view plaincopyprint?
#import?"MyTableViewOneMessage.h" ???? ?? @implementation?MyTableViewOneMessage?? ?? @synthesize?mylable;?? @synthesize?message;?? ?? -?(id)initWithNibName:(NSString?*)nibNameOrNil?bundle:(NSBundle?*)nibBundleOrNil?? {?? ????self?=?[super?initWithNibName:nibNameOrNil?bundle:nibBundleOrNil];?? ????if ?(self)?{?? ?????????? ????}?? ????return ?self;?? }?? ?? -(void )viewDidAppear:(BOOL )animated{?? ????self.mylable.text?=?message;?? }?? ?? -?(void )dealloc?? {?? ????[mylable?release];?? ????[message?release];?? ????[super?dealloc];?? }?? ?? -?(void )didReceiveMemoryWarning?? {?? ?????? ????[super?didReceiveMemoryWarning];?? ?????? ?????? }?? ?? #pragma?mark?-?View?lifecycle ???? -?(void )viewDidLoad?? {?? ????self.navigationItem.title?=?@"Tableview傳過來的值" ;?? ????[super?viewDidLoad];?? ?????? }?? ?? -?(void )viewDidUnload?? {?? ????[super?viewDidUnload];?? ?????? ?????? }?? ?? -?(BOOL )shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation?? {?? ?????? ????return ?(interfaceOrientation?==?UIInterfaceOrientationPortrait);?? }?? ?? @end??
#import "MyTableViewOneMessage.h"@implementation MyTableViewOneMessage@synthesize mylable;
@synthesize message;- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];if (self) {// Custom initialization}return self;
}-(void)viewDidAppear:(BOOL)animated{self.mylable.text = message;
}- (void)dealloc
{[mylable release];[message release];[super dealloc];
}- (void)didReceiveMemoryWarning
{// Releases the view if it doesn't have a superview.[super didReceiveMemoryWarning];// Release any cached data, images, etc that aren't in use.
}#pragma mark - View lifecycle- (void)viewDidLoad
{self.navigationItem.title = @"Tableview傳過來的值";[super viewDidLoad];// Do any additional setup after loading the view from its nib.
}- (void)viewDidUnload
{[super viewDidUnload];// Release any retained subviews of the main view.// e.g. self.myOutlet = nil;
}- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{// Return YES for supported orientationsreturn (interfaceOrientation == UIInterfaceOrientationPortrait);
}@end
總結(jié)
以上是生活随笔 為你收集整理的Iphone表视图的简单操作 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。