表视图的范例

来源:互联网 发布:visual mac 编辑:程序博客网 时间:2024/05/17 08:27

[转载地址]:http://blog.csdn.net/riveram/article/details/7340479

 

1.创建一个Navigation—based—Application项目,这样Interface Builder中会自动生成一个Table View,然后将Search Bar拖放到表示图上,以我们要给表示图添加搜索功能,不要忘记将Search Bar的delegate连接到File‘s Owner项,然后将Search Bar与searchBar变量连接。

2.在Resources文件夹下创建一个Movies.plist文件,然后为该文件添加一些数据,如下图:


3.在.h头文件添加如下内容:

[cpp] view plaincopyprint?
  1. #import <UIKit/UIKit.h>   
  2.   
  3.   
  4. @interface MyTableView : UITableViewController <UISearchBarDelegate>{  
  5.     NSDictionary *movieTitles;  
  6.     NSArray *years;  
  7.       
  8.     IBOutlet UISearchBar *searchBar;  
  9.       
  10.     BOOL isSearchOn;  
  11.     BOOL canSelectRow;  
  12.       
  13.     //下面两个是搜索用到的两个变量   
  14.     NSMutableArray *listOfMovies;  
  15.     NSMutableArray *searchResult;  
  16. }  
  17. @property(nonatomic,retain) NSDictionary *movieTitles;  
  18. @property(nonatomic,retain)NSArray *years;  
  19. @property(nonatomic,retain)UISearchBar *searchBar;  
  20.   
  21. -(void)donSearching:(id)sender;  
  22. -(void)searchMoviesTableView;  
  23. @end  

4.当加载View窗口时,首先定位属性列表并把这个列表加载到listOfMovies中,然后将所有的年份提取到years中,然后添加搜索条并初始化搜索条用到的数据:

[cpp] view plaincopyprint?
  1. //读取Movies.plist文件的内容到变量里面   
  2. - (void)viewDidLoad  
  3. {  
  4.    NSString *path = [[NSBundle mainBundle]pathForResource:@"Movies" ofType:@"plist"];  
  5.     NSDictionary *dic = [[NSDictionary alloc]initWithContentsOfFile:path];  
  6.     self.movieTitles = dic;  
  7.     [dic release];  
  8.       
  9.     NSArray *array = [[self.movieTitles allKeys]sortedArrayUsingSelector:@selector(compare:)];  
  10.     self.years = array;  
  11.       
  12.     //下面两句是添加搜索条   
  13.     self.tableView.tableHeaderView = searchBar;  
  14.     self.searchBar.autocorrectionType = UITextAutocorrectionTypeYes;  
  15.       
  16.     //初始化listofmovies   
  17.     listOfMovies = [[NSMutableArray alloc]init];  
  18.     for (NSString *year in years) {  
  19.         NSArray *movies = [movieTitles objectForKey:year];  
  20.         for(NSString *title in movies){  
  21.             [listOfMovies addObject:title];  
  22.         }  
  23.     }  
  24.   
  25.     searchResult = [[NSMutableArray alloc]init];  
  26.       
  27.     isSearchOn = NO;  
  28.     canSelectRow = YES;  
  29.     [super viewDidLoad];  
  30.   
  31. }  

5.在自动生成的方法numberOfSectionsInTableView中添加如下代码,表示告诉表示图一共分多少节:

[cpp] view plaincopyprint?
  1. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView  
  2. {  
  3.     if (isSearchOn) {  
  4.         return 1;//如果正在搜索就只有一个section  
  5.     }  
  6.   else  
  7.     return [self.years count];  
  8. }  
6.在自动生成的方法tableView:numberOfRowsInSection:中添加如下代码,表示告诉表视图每一节显示多少行:

[cpp] view plaincopyprint?
  1. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
  2. {  
  3.   
  4.     if (isSearchOn) {  
  5.         return [searchResult count];  
  6.     }else{  
  7.     // Return the number of rows in the section.  
  8.     NSString *year = [self.years objectAtIndex:section];  
  9.     NSArray *movieSection = [self.movieTitles objectForKey:year];  
  10.     return [movieSection count];  
  11.     }  
  12. }  
7.在自动生成的方法tableView:cellForRowAtIndexPath:中添加如下代码,为每一行设值:

[cpp] view plaincopyprint?
  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.     static NSString *CellIdentifier = @"Cell";  
  4.       
  5.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
  6.     if (cell == nil) {  
  7.         cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];  
  8.     }  
  9.       
  10.     if (isSearchOn) {  
  11.         NSString *cellValue = [searchResult objectAtIndex:indexPath.row];  
  12.         cell.textLabel.text = cellValue;  
  13.     }else{  
  14.     NSString *year = [self.years objectAtIndex:[indexPath section]];//得到当前行所在的section  
  15.     NSArray *movieSection = [self.movieTitles objectForKey:year];  
  16.     cell.textLabel.text = [movieSection objectAtIndex:[indexPath row]];  
  17.           
  18.         cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;  
  19.     }  
  20.       
  21.     //为每一行添加图片   
  22.     UIImage *image = [UIImage imageNamed:@"apple.jpeg"];  
  23.     cell.imageView.image = image;  
  24.       
  25.     return cell;  
  26. }  
8.实现tableView:titleForHeaderInSection:方法,将得到的年份作为每一节的Header:

[cpp] view plaincopyprint?
  1. //设置每个section的标题   
  2. -(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{  
  3.     NSString *year = [self.years objectAtIndex:section];  
  4.     if (isSearchOn) {  
  5.         return nil;  
  6.     }  
  7.     else{  
  8.     return year;  
  9.     }  
  10.     }  
9.为表格添加索引,只需要实现sectionIndexTitlesForTableView:方法,该方法返回每一节的Header数组:

[cpp] view plaincopyprint?
  1. //添加索引   
  2. -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{  
  3.     if (isSearchOn)   
  4.         return nil;  
  5.     else  
  6.     return years;  
  7. }  
10.当用户点击搜索栏会促发searchBarTextDidBeginEditing:事件(UISearchBarDelegate协议中定义的一个方法,我们在.h头文件中实现了这个协议),在该方法中,向屏幕右上角添加一个Done按钮,当用户点击Done按钮时会调用doneSearching方法:

[cpp] view plaincopyprint?
  1. //搜索筐得到焦点后   
  2. -(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{  
  3.     isSearchOn = YES;  
  4.     canSelectRow = NO;  
  5.     self.tableView.scrollEnabled = NO;  
  6.     //添加down按钮及其点击方法   
  7.     self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(donSearching:)]autorelease];  
  8. }  
11.doneSearching方法使得搜索栏移除了First Responder状态,因而会隐藏键盘,同时,通过调用表视图的reloadData方法重新加载表视图:

[cpp] view plaincopyprint?
  1. //点击down按钮后   
  2. -(void)donSearching:(id)sender{  
  3.     isSearchOn = NO;  
  4.     canSelectRow = YES;  
  5.     self.tableView.scrollEnabled = YES;  
  6.     self.navigationItem.rightBarButtonItem = nil;  
  7.       
  8.     [searchBar resignFirstResponder];  
  9.       
  10.     [self.tableView reloadData];  
  11. }  
12.当用户在搜索栏中输入时,输入的每个字符都会触发searchBar:textDidChange:事件,只要搜索栏中有一个字符,就会调用searchMoviesTableView方法:

[cpp] view plaincopyprint?
  1. //搜索筐里面的文字改变后   
  2. -(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{  
  3.     if ([searchText length]>0) {  
  4.         isSearchOn = YES;  
  5.         canSelectRow = YES;  
  6.         self.tableView.scrollEnabled = YES;  
  7.         [self searchMoviesTableView];//调用搜索方法  
  8.     }  
  9.     else{  
  10.         isSearchOn = NO;  
  11.         canSelectRow = NO;  
  12.         self.tableView.scrollEnabled = NO;  
  13.     }  
  14.     [self.tableView reloadData];  
  15. }  
13.searchMoviesTableView方法会搜索listOfMovies数组,通过NSString类的rangeOfString:options:方法,使用特定的字符串对每个名称进行搜索,返回的结果是一个nsRange对象,如果长度大于0就表示有一个匹配结果,将它添加到searchResult书组中:

[cpp] view plaincopyprint?
  1. //自定义的搜索方法,得到搜索结果   
  2. -(void)searchMoviesTableView{  
  3.     [searchResult removeAllObjects];  
  4.     for (NSString *str in listOfMovies) {  
  5.         NSRange titleResultsRange = [str rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];  
  6.         if (titleResultsRange.length > 0) {  
  7.             [searchResult addObject:str];  
  8.         }  
  9.     }  
  10. }  
14.当用户点击键盘上的Search按钮时,就会调用如下方法:

[cpp] view plaincopyprint?
  1. -(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar{  
  2.     [self searchMoviesTableView];  
  3. }  
15.新建一个新的文件,该文件在后面定义,点击表格的某一行后就会调转到该页面去并将点击的那一样的名称传过去,要想做到这一点必须实现如下方法:

[cpp] view plaincopyprint?
  1. //点击table某一行跳转页面   
  2. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  
  3. {  
  4.     MyTableViewOneMessage *mytm = [[MyTableViewOneMessage alloc]initWithNibName:@"MyTableViewOneMessage" bundle:nil];  
  5.       
  6.     NSString *year = [self.years objectAtIndex:[indexPath section]];  
  7.     NSArray *movieSection = [self.movieTitles objectForKey:year];  
  8.     NSString *movieTitle = [movieSection objectAtIndex:[indexPath row]];  
  9.     NSString *message = [[NSString alloc]initWithFormat:@"%@",movieTitle];  
  10.     mytm.message = message;  
  11.     [self.navigationController pushViewController:mytm animated:YES];  
  12.     [mytm release];  
  13. }  
16.新添加的页面很简单,主要用来测试表格的点击事件,导航然后显示传过来的字符串:

Interface Builder中添加两个lable,具体的就不详细了,很简单的,下面是这个界面的.h和.m文件:

[cpp] view plaincopyprint?
  1. #import <UIKit/UIKit.h>   
  2.   
  3.   
  4. @interface MyTableViewOneMessage : UIViewController {  
  5.     IBOutlet UILabel *mylable;  
  6.     NSString *message;  
  7. }  
  8.   
  9. @property(nonatomic,retain)UILabel *mylable;  
  10. @property(nonatomic,retain)NSString *message;  
  11.   
  12. @end  
[cpp] view plaincopyprint?
  1. #import "MyTableViewOneMessage.h"  
  2.   
  3.   
  4. @implementation MyTableViewOneMessage  
  5.   
  6. @synthesize mylable;  
  7. @synthesize message;  
  8.   
  9. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil  
  10. {  
  11.     self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];  
  12.     if (self) {  
  13.         // Custom initialization  
  14.     }  
  15.     return self;  
  16. }  
  17.   
  18. -(void)viewDidAppear:(BOOL)animated{  
  19.     self.mylable.text = message;  
  20. }  
  21.   
  22. - (void)dealloc  
  23. {  
  24.     [mylable release];  
  25.     [message release];  
  26.     [super dealloc];  
  27. }  
  28.   
  29. - (void)didReceiveMemoryWarning  
  30. {  
  31.     // Releases the view if it doesn't have a superview.  
  32.     [super didReceiveMemoryWarning];  
  33.       
  34.     // Release any cached data, images, etc that aren't in use.  
  35. }  
  36.   
  37. #pragma mark - View lifecycle  
  38.   
  39. - (void)viewDidLoad  
  40. {  
  41.     self.navigationItem.title = @"Tableview传过来的值";  
  42.     [super viewDidLoad];  
  43.     // Do any additional setup after loading the view from its nib.  
  44. }  
  45.   
  46. - (void)viewDidUnload  
  47. {  
  48.     [super viewDidUnload];  
  49.     // Release any retained subviews of the main view.  
  50.     // e.g. self.myOutlet = nil;   
  51. }  
  52.   
  53. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  54. {  
  55.     // Return YES for supported orientations  
  56.     return (interfaceOrientation == UIInterfaceOrientationPortrait);  
  57. }  
  58.   
  59. @end  

原创粉丝点击