zoukankan      html  css  js  c++  java
  • 表视图控制器(TableViewController)(三) 、 表视图搜索

    1 乐库的设置界面

    1.1 问题

    tableView分为静态(static)和动态(dynamic),之前使用的都是动态的tableView,表视图的有多少分区、有多少行以及每一行显示的内容都不是固定的,都由数据模式来决定。而静态的tableView有多少分区、有多少行以及每一行显示的内容都是固定不变的。

    静态tableView应用广泛,常用于各种应用软件的设置界面,本案例使用静态tableView完成乐库的设置界面,如图-1所示:

    图-1

    1.2 方案

    由图-1可以看到该界面的显示内容是固定不变的,不需要根据数据模型而变化,所以该页面是一个静态的tableView。

    首先还是创建一个带有导航的TRMusicConfigureTableViewController的表视图控制器,作为根视图控制器,并在TRMusicConfigureTableViewController.m文件中通过tableView的协议方法固定表视图的分区数和行数。

    其次在xib文件中将tableView的style设置为Grouped。从对象库中拖拽一个UIView对象到xib中,作为tableView的tableheaderView。在该UIView视图上拖放一个UIImageView对象和四个UIButton对象,并在右边栏的检查器中设置相关的属性。

    然后在xib文件中拖放四个UITableViewCell对象,根据界面需求从对象库中拖放控件到cell上面,完成每个cell的界面布局。

    最后关联xib中的每个UITableViewCell对象和UIView对象为TRMusicConfigureTableViewController的私有属性,在viewDidLoad方法里面设置tableHeaderView,在tableView的协议方法cellForRowAtIndexPath里面指定每个cell对象。

    1.3 步骤

    实现此案例需要按照如下步骤进行。

    步骤一:创建TRMusicConfigureTableViewController类

    创建TRMusicConfigureTableViewController类继承至UITableViewController,然后在TRAppDelegate.m文件的程序入口方法中创建一个带有导航的表视图控制器作为根视图控制器,代码如下所示:

    1. -(BOOL)application:(UIApplication *)application
    2. didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    3. self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    4. TRMusicConfigureTableViewController *musicTVC = [[TRMusicConfigureTableViewController alloc]initWithNibName:@"TRMusicConfigureTableViewController" bundle:nil];
    5. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:musicTVC];
    6. self.window.rootViewController = navi;
    7. [self.window makeKeyAndVisible];
    8. return YES;
    9. }

    然后在TRMusicConfigureTableViewController.m文件中通过协议方法确定表视图的分区和行数,由于是静态的tableView所以分区和行数都是固定的,代码如下所示:

    1. //返回4个分区
    2. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    3. {
    4. return 4;
    5. }
    6. //确定每个分区的行数
    7. -(NSInteger)tableView:(UITableView *)tableView
    8. numberOfRowsInSection:(NSInteger)section
    9. {
    10. switch (section) {
    11. case 0:return 1;
    12. case 1:return 4;
    13. case 2:return 1;
    14. case 3:return 1;
    15. }
    16. return 0;
    17. }

    步骤二:创建tableHeaderView视图

    选中xib文件中的tableView,在右边栏的第四个检查中将tableView的style设置为Grouped,以分区的形式展示表视图,如图-2所示:

    图-2

    xib文件中除了可以创建一个视图控制器的视图,还可以创建任何UIView对象,比如一个UITableViewCell对象,xib中的每一个对象都会在viewDidLoad方法完成前被创建。一般情况,xib中只有一个对象是和控制器类的view绑定在一起的,其他对象一般会做为控制器的属性存在。

    在这里先创建tableViewHeader视图对象,从对象库中拖拽一个UIView对象到xib文件中,默认的UIView对象是和屏幕一样的大小,并且带有状态栏,由于该UIView对象是tableView的tableHeaderView视图,并不需要和屏幕一样的大小,也不需要有状态栏。所以选中右边栏的第四个检查器,将Size设置为Freeform,StatusBar设置为None,如图-3所示:

    图-3

    最后从对象库中拖放一个UIImageView对象和四个UIButton对象到UIView对象中,并在右边栏的第四个检查器中设置相关属性,完成tableHeaderView的界面,如图-4所示:

    图-4

    步骤三:创建UITableViewCell对象

    在xib文件中拖放七个UITableViewCell对象,依次按照界面的需求,从对象库中拖放相应的控件到每个cell的contentView中,并在在右边栏的检查器中对各控件的属性进行设置,完成每个cell的界面,如图-5所示:

    图-5

    这里“定时开关”单元格还有一个UISwitch控件的辅助视图,添加辅助视图首先从对象库中拖拽一个UISwitch对象到xib中,然后选中“定时开关”单元格,在右边栏的第六个检查器中选中accessoryView后面的空心小圆圈往UISwitch控件上拖拽,释放鼠标,:accessoryView后面的空心小圆圈变成实心即表示已将“定时开关”单元格的辅助视图和UISwitch对象关联上,如图-6所示:

    图-6

    选中UISwitch对象,点击鼠标右键也可以查看,如图-7所示:

    图-7

    步骤四:关联属性,设置tableHeaderView和每个单元格

    选中xib文件的中的headerView视图,将其关联成TRMusicConfigureTableViewController的私有属性headerView,将xib中headerView上的UIImageView视图关联成TRMusicConfigureTableViewController的私有属性userImageView,然后在viewDidLoad方法里面对表视图的tableHeaderView进行设置,代码如下所示:

    1. @property (weak, nonatomic) IBOutlet UIView *headerView;
    2. @property (weak, nonatomic) IBOutlet UIImageView *userImageView;
    3. - (void)viewDidLoad
    4. {
    5. [super viewDidLoad];
    6. self.title = @"更多";
    7. //设置表视图的表头视图
    8. self.tableView.tableHeaderView = self.headerView;
    9. self.userImageView.image = [UIImage imageNamed:@"Rainbow.ico"];
    10. }

    然后将xib中的七个cell视图关联成TRMusicConfigureTableViewController的私有属性,代码如下所示:

    1. @property (strong, nonatomic) IBOutlet UITableViewCell *myGreenDiamondCell;
    2. @property (strong, nonatomic) IBOutlet UITableViewCell *settingCell;
    3. @property (strong, nonatomic) IBOutlet UITableViewCell *packageCell;
    4. @property (strong, nonatomic) IBOutlet UITableViewCell *qplayCell;
    5. @property (strong, nonatomic) IBOutlet UITableViewCell *closeCell;
    6. @property (strong, nonatomic) IBOutlet UITableViewCell *aboutCell;
    7. @property (strong, nonatomic) IBOutlet UITableViewCell *exitCell;

    这里需要注意在关联属性时,属性的设置应该选择strong而不是weak,如果是弱引用在viewDidLoad方法执行完毕xib创建的cell对象没有被任何对象持有,那么出了viewDidLoad方法cell对象就会被释放,后面在协议方法cellForRowAtIndexPath方法里面设置每行cell单元格时得不到cell对象程序就会报错。

    最后在协议方法cellForRowAtIndexPath方法里面设定每一行的cell对象,代码如下所示:

    1. -(UITableViewCell *)tableView:(UITableView *)tableView
    2. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    3. {
    4. if(indexPath.section==0&&indexPath.row==0) {
    5. return self.myGreenDiamondCell;
    6. }else if(indexPath.section==1&&indexPath.row==0){
    7. return self.settingCell;
    8. }else if(indexPath.section==1&&indexPath.row==1){
    9. return self.packageCell;
    10. }else if(indexPath.section==1&&indexPath.row==2){
    11. return self.qplayCell;
    12. }else if(indexPath.section==1&&indexPath.row==3){
    13. return self.closeCell;
    14. }else if(indexPath.section==2){
    15. return self.aboutCell;
    16. }else{
    17. return self.exitCell;
    18. }
    19. }

    1.4 完整代码

    本案例中,TRAppDelegate.m文件中的完整代码如下所示:

     
    1. #import "TRAppDelegate.h"
    2. #import "TRMusicConfigureTableViewController.h"
    3. @implementation TRAppDelegate
    4. -(BOOL)application:(UIApplication *)application
    5. didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    6. {
    7. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    8. self.window.backgroundColor = [UIColor whiteColor];
    9. TRMusicConfigureTableViewController *musicTVC = [[TRMusicConfigureTableViewController alloc]initWithNibName:@"TRMusicConfigureTableViewController" bundle:nil];
    10. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:musicTVC];
    11. self.window.rootViewController = navi;
    12. [self.window makeKeyAndVisible];
    13. return YES;
    14. }
    15. @end
     

    本案例中,TRMusicConfigureTableViewController.m文件中的完整代码如下所示:

     
    1. #import "TRMusicConfigureTableViewController.h"
    2. @interface TRMusicConfigureTableViewController ()
    3. @property (strong, nonatomic) IBOutlet UITableViewCell *myGreenDiamondCell;
    4. @property (strong, nonatomic) IBOutlet UITableViewCell *settingCell;
    5. @property (strong, nonatomic) IBOutlet UITableViewCell *packageCell;
    6. @property (strong, nonatomic) IBOutlet UITableViewCell *qplayCell;
    7. @property (strong, nonatomic) IBOutlet UITableViewCell *closeCell;
    8. @property (strong, nonatomic) IBOutlet UITableViewCell *aboutCell;
    9. @property (strong, nonatomic) IBOutlet UITableViewCell *exitCell;
    10. @property (weak, nonatomic) IBOutlet UIView *headerView;
    11. @property (weak, nonatomic) IBOutlet UIImageView *userImageView;
    12. @end
    13. @implementation TRMusicConfigureTableViewController
    14. - (void)viewDidLoad
    15. {
    16. [super viewDidLoad];
    17. self.title = @"更多";
    18. self.tableView.tableHeaderView = self.headerView;
    19. self.userImageView.image = [UIImage imageNamed:@"Rainbow.ico"];
    20. }
    21. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    22. {
    23. return 4;
    24. }
    25. -(NSInteger)tableView:(UITableView *)tableView
    26. numberOfRowsInSection:(NSInteger)section
    27. {
    28. switch (section) {
    29. case 0:return 1;
    30. case 1:return 4;
    31. case 2:return 1;
    32. case 3:return 1;
    33. }
    34. return 0;
    35. }
    36. -(UITableViewCell *)tableView:(UITableView *)tableView
    37. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    38. {
    39. if(indexPath.section==0&&indexPath.row==0) return self.myGreenDiamondCell;
    40. else if(indexPath.section==1&&indexPath.row==0) return self.settingCell;
    41. else if(indexPath.section==1&&indexPath.row==1) return self.packageCell;
    42. else if(indexPath.section==1&&indexPath.row==2) return self.qplayCell;
    43. else if(indexPath.section==1&&indexPath.row==3) return self.closeCell;
    44. else if(indexPath.section==2) return self.aboutCell;
    45. else return self.exitCell;
    46. }
    47. @end
     

    2 复杂的表视图展示

    2.1 问题

    之前的案例都是使用的系统提供的UITableViewController类,实现一个表视图控制器管理一个表视图,给一个表视图加载数据。在实际开发中也经常会遇到一个视图控制器管理多个表视图,给多个表视图加载数据的情况,本案例将学习如何使用一个视图控制器管理两个表视图,同时给两个表视图加载数据,如图-8所示:

    图-8

    2.2 方案

    首先创建一个SingleViewApplication项目,然后创建一个带有导航的TRViewController视图控制器作为根视图控制器。在xib文件中的view视图上拖放一个UITableView对象,并关联成TRViewController的属性tableView1,将tableView1的dataSouce和delegate以拉线的形式设置为TRViewController。

    其次在xib的界面上拖放一个UISlider对象并关联成TRViewController的方法,主要实现功能是拖动滑块能控制tableView1在界面中的显示第几行单元格。

    然后定义一个UITableView私有属性tableView2,并在viewDidLoad方法里面创建该对象,将tableView2的dataSouce和delegate以代码的形式设置为TRViewController,最后将tableView2添加到父视图中。

    最后在TRViewController.m文件中通过实现协议方法给tableView1和tableView2加载数据。

    2.3 步骤

    实现此案例需要按照如下步骤进行。

    步骤一:在xib中创建tableView1

    首先创建一个SingleViewApplication项目,然后在TRAppDelegate中创建一个带有导航的TRViewController视图控制器作为根视图控制器,代码如下所示:

     
    1. -(BOOL)application:(UIApplication *)application
    2. didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    3. {
    4. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    5. self.window.backgroundColor = [UIColor whiteColor];
    6. TRViewController *vc = [[TRViewController alloc]initWithNibName:@"TRViewController" bundle:nil];
    7. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:vc];
    8. self.window.rootViewController = navi;
    9. [self.window makeKeyAndVisible];
    10. return YES;
    11. }

    然后在xib文件中的view视图上拖放一个UITableView对象,并关联成TRViewController的私有属性tableView1,代码如下所示:

    1. @property (weak, nonatomic) IBOutlet UITableView *tableView1;

    在xib文件中选中tableView对象,点击右键选择dataSouce和delegate后面的空心小圆圈拖拽到File’s Owner,即将tableView的dataSource和delegate设置为了TRViewController,如图-9所示:

    图-9

    步骤二:在xib中创UISlider对象

    在xib界面上拖拽一个UISlider控件,在右边栏的第四个检查器中将miniMum、maxiMum和current分别设置为0、1和0,然后将slider关联成TRViewController的方法sliderValueChange:,该方法主要实现功能是拖动滑块能控制tableView1在界面中的显示第几行单元格,在方法里面根据slider的value值计算出tableView的contentOffset即可,代码如下所示:

    1. - (IBAction)sliderValueChange:(UISlider *)sender
    2. {
    3. CGFloat height = self.tableView1.contentSize.height;
    4. CGFloat scrollVal = sender.value * height;
    5. CGPoint offset = CGPointMake(self.tableView1.contentOffset.x, scrollVal);
    6. self.tableView1.contentOffset = offset;
    7. }

    步骤三:使用代码创建tableView2对象

    首先在TRViewController中定义一个UITableView类型的私有属性,然后在viewDidLoad方法里面创建tableView2对象,根据屏幕和tableView1的位置大小设置tableView2的frame属性,代码如下所示:

     
    1. //定义属性tableView2
    2. @property (strong, nonatomic) UITableView *tableView2;
    3. //viewDidLoad方法里面创建tableView2对象
    4. - (void)viewDidLoad
    5. {
    6. [super viewDidLoad];
    7. self.title = @"TableView";
    8. CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    9. CGRect frame = CGRectMake(0, self.tableView1.frame.size.height, 320, screenSize.height-self.tableView1.frame.size.height);
    10. self.tableView2 = [[UITableView alloc]initWithFrame:frame style:UITableViewStylePlain];
    11. }

    然后使用代码将tableView2的dataSource和delegate赋值为TRViewController,代码如下所示:

     
    1. - (void)viewDidLoad
    2. {
    3. [super viewDidLoad];
    4. self.title = @"TableView";
    5. CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    6. CGRect frame = CGRectMake(0, self.tableView1.frame.size.height, 320, screenSize.height-self.tableView1.frame.size.height);
    7. self.tableView2 = [[UITableView alloc]initWithFrame:frame style:UITableViewStylePlain];
    8. //设置tableView2的dataSource和delegate
    9. self.tableView2.delegate = self;
    10. self.tableView2.dataSource = self;
    11. [self.view addSubview:self.tableView2];
    12. }

    步骤四:给tableView1和tableView2加载数据

    首先实现协议方法tableView:numberOfRowsInSection:告诉两个tableView分别显示多少行,由于两个tableView在加载数据时都会调用此方法,因此需要在方法里面根据tableView参数做一个判断,判断当前调用此方法的是tableView1还是tableView2,本案例让tableView1显示50行,tableView2显示10行,代码如下所示:

     
    1. -(NSInteger)tableView:(UITableView *)tableView
    2. numberOfRowsInSection:(NSInteger)section
    3. {
    4. if (tableView == self.tableView1) {
    5. return 50;
    6. }else{
    7. return 10;
    8. }
    9. }

    然后在协议方法tableView:cellForRowAtindexPath:里面创建cell对象,同样需要根据tableView参数区分tableView1和tableView2,代码如下所示:

     
    1. -(UITableViewCell *)tableView:(UITableView *)tableView
    2. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    3. {
    4. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
    5. if (cell==nil) {
    6. cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"];
    7. }
    8. if(tableView == self.tableView1){
    9. cell.textLabel.text = [NSString stringWithFormat:@"Hello World. %d", indexPath.row];
    10. }else{
    11. [cell.contentView setBackgroundColor:[UIColor yellowColor]];
    12. cell.textLabel.text = @"这是tableView2的数据";
    13. }
    14. return cell;
    15. }

    最后实现协议方法tableView:didSelectRowAtIndexPath:,该方法在点击单元格时会被调用,同样的需要根据tableView参数区分tableView1和tableView2,代码如下所示:

    1. -(void)tableView:(UITableView *)tableView
    2. didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    3. {
    4. if (tableView == self.tableView1) {
    5. NSLog(@"用户点击了%d行", indexPath.row);
    6. }else{
    7. NSLog(@"这是tableView2");
    8. }
    9. }

    2.4 完整代码

    本案例中,TRAppDelegate.m文件中的完整代码如下所示:

     
    1. #import "TRAppDelegate.h"
    2. #import "TRViewController.h"
    3. @implementation TRAppDelegate
    4. -(BOOL)application:(UIApplication *)application
    5. didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    6. {
    7. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    8. self.window.backgroundColor = [UIColor whiteColor];
    9. TRViewController *vc = [[TRViewController alloc]initWithNibName:@"TRViewController" bundle:nil];
    10. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:vc];
    11. self.window.rootViewController = navi;
    12. [self.window makeKeyAndVisible];
    13. return YES;
    14. }
    15. @end
     

    本案例中,TRViewController.m文件中的完整代码如下所示:

     
    1. #import "TRViewController.h"
    2. @interface TRViewController () <UITableViewDataSource, UITableViewDelegate>
    3. @property (weak, nonatomic) IBOutlet UITableView *tableView1;
    4. @property (strong, nonatomic) UITableView *tableView2;
    5. @end
    6. @implementation TRViewController
    7. - (void)viewDidLoad
    8. {
    9. [super viewDidLoad];
    10. self.title = @"TableView";
    11. CGSize screenSize = [[UIScreen mainScreen] bounds].size;
    12. CGRect frame = CGRectMake(0, self.tableView1.frame.size.height, 320, screenSize.height-self.tableView1.frame.size.height);
    13. self.tableView2 = [[UITableView alloc]initWithFrame:frame style:UITableViewStylePlain];
    14. self.tableView2.delegate = self;
    15. self.tableView2.dataSource = self;
    16. [self.view addSubview:self.tableView2];
    17. }
    18. -(NSInteger)tableView:(UITableView *)tableView
    19. numberOfRowsInSection:(NSInteger)section
    20. {
    21. if (tableView == self.tableView1) {
    22. return 50;
    23. }else{
    24. return 10;
    25. }
    26. }
    27. -(UITableViewCell *)tableView:(UITableView *)tableView
    28. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    29. {
    30. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
    31. if (cell==nil) {
    32. cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyCell"];
    33. }
    34. if(tableView == self.tableView1){
    35. cell.textLabel.text = [NSString stringWithFormat:@"Hello World. %d", indexPath.row];
    36. }else{
    37. [cell.contentView setBackgroundColor:[UIColor yellowColor]];
    38. cell.textLabel.text = @"这是tableView2的数据";
    39. }
    40. return cell;
    41. }
    42. -(void)tableView:(UITableView *)tableView
    43. didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    44. {
    45. if (tableView == self.tableView1) {
    46. NSLog(@"用户点击了%d行", indexPath.row);
    47. }else{
    48. NSLog(@"这是tableView2");
    49. }
    50. }
    51. - (IBAction)sliderValueChange:(UISlider *)sender
    52. {
    53. CGFloat height = self.tableView1.contentSize.height;
    54. CGFloat scrollVal = sender.value * height;
    55. CGPoint offset = CGPointMake(self.tableView1.contentOffset.x, scrollVal);
    56. self.tableView1.contentOffset = offset;
    57. }
    58. @end
     

    3 下拉后重新获取模型中数据

    3.1 问题

    下拉刷新是手机应用经常使用的一种功能,苹果在ios6中推出了下拉刷新控件,本案例通过使用下拉刷新控件实现每次下拉刷新获取当前时间,如图-10所示:

    图-10

    3.2 方案

    UITableViewController有一个refreshControl控件,该控件是一个UIRefreshControl类型,主要为了表视图实现下拉刷新而提供的类,该类型只能用于表视图界面,当设置refreshControl属性之后,表视图控制器会自动将其放置表视图中。

    首先同样创建一个SingleViewApplication项目,然后创建一个带有导航的TRTableViewController视图控制器作为根视图控制器。定义一个NSMutableArray类型的私有属性logs用于管理数据源,在viewDidLoad方法中初始化数组logs,并获取当前时间对象添加到数组中。

    其次在viewDidLoad方法里面创建一个UIRefreshControl对象refreshControl,将其设置为TRTableViewController的refreshControl属性,通过addTarget:action:forControlEvents:方法给刷新控件添加事件,当下拉刷新时获取新的数据。

    然后实现获取新数据的方法,本案例中就是该方法内重新获取当前时间,并将其添加到数据源数组中。

    最后在刷新完成之后,表视图更新数据和界面。

    3.3 步骤

    实现此案例需要按照如下步骤进行。

    步骤一:创建TRTableViewController视图控制器

    首先创建一个带有导航的TRTableViewController视图控制器作为根视图控制器。在TRTableViewController类中定义一个NSMutableArray类型的私有属性loges用于管理表视图需要显示的数据,本案例中就是管理的每次刷新获取的时间数据,代码如下所示:

    1. //定义logs属性
    2. @interface TRTableViewController ()
    3. @property (nonatomic,strong)NSMutableArray *logs;
    4. @end
    5. //在viewDidLoad方法里面初始化数组
    6. - (void)viewDidLoad {
    7. [super viewDidLoad];
    8. //初始化数组和时间
    9. self.logs = [@[]mutableCopy];
    10. NSDate *date = [NSDate date];
    11. [self.logs addObject:date];
    12. }

    然后在TRTableViewController类中实现协议方法,给表视图加载数据,代码如下所示:

     
    1. -(NSInteger)tableView:(UITableView *)tableView
    2. numberOfRowsInSection:(NSInteger)section {
    3. return self.logs.count;
    4. }
    5. -(UITableViewCell *)tableView:(UITableView *)tableView
    6. cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    7. static NSString *cellIdentifer = @"Cell";
    8. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
    9. if (!cell) {
    10. cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer];
    11. }
    12. NSDate *date = self.logs[indexPath.row];
    13. NSDateFormatter *df = [[NSDateFormatter alloc]init];
    14. [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    15. cell.textLabel.text = [df stringFromDate:date];
    16. return cell;
    17. }

    步骤二:创建UIRefreshControl对象

    在viewDidLoad方法里面创建一个UIRefreshControl对象refreshControl,并设置refreshControl的下拉显示标题attributedTitle,这里attributedTitle是一个NSAtrributedString类型的字符串,代码如下所示:

     
    1. //创建一个refreshControl对象
    2. UIRefreshControl *refreshControl = [[UIRefreshControl alloc]init];
    3. //设置refreshControl的标题
    4. refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];

    然后使用addTarget:action:forControlEvents:方法给refreshControl添加事件处理方法,这里的action:参数传递的方法主要功能就是获取新数据,event参数选择UIControlEventValueChanged,代码如下所示:

    1. [refreshControl addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];

    最后将创建好的下拉刷新控件对象设置为TRTableViewController的refreshControl属性,代码如下所示:

    1. //让self.refreshControl指向refreshControl
    2. self.refreshControl = refreshControl;

    步骤三:实现获取新数据方法refreshTableView

    在refreshTableView方法的功能主要是获取新数据,在实际的应用开发中这里通常都是发送网络请求或者数据库查询来获取新数据,本案例使用获取当前时间来模拟实现,代码如下所示:

    1. -(void)refreshTableView{
    2. //isRefreshing属性主要用于判断是否处于下拉刷新状态
    3. if (self.refreshControl.isRefreshing) {
    4. self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"加载中......"];
    5. //模拟获取新数据,重新获取当前时间
    6. NSDate *date = [NSDate date];
    7. [self.logs addObject:date];
    8. //模拟新数据获取完成之后,延迟2秒调用endRefreshData方法
    9. [self performSelector:@selector(endRefreshData) withObject:nil afterDelay:2];
    10. }
    11. }

    以上代码中使用performSelector:withObject:afterDelay:方法来延迟2秒调用endRefreshData方法,用于模拟实现数据获取完成之后的操作。

    然后实现endRefreshData方法,该方法内部首先让刷新控件结束刷新,然后让tableView更新数据和界面,代码如下所示:

     
    1. -(void)endRefreshData{
    2. //刷新控件结束刷新
    3. [self.refreshControl endRefreshing];
    4. //表视图更新数据
    5. [self.tableView reloadData];
    6. }

    3.4 完整代码

    本案例中,TRTableViewController.m文件中的完整代码如下所示:

     
    1. #import "TRTableViewController.h"
    2. @interface TRTableViewController ()
    3. @property (nonatomic,strong)NSMutableArray *logs;
    4. @end
    5. @implementation TRTableViewController
    6. - (void)viewDidLoad {
    7. [super viewDidLoad];
    8. //初始化数组和时间
    9. self.logs = [@[]mutableCopy];
    10. NSDate *date = [NSDate date];
    11. [self.logs addObject:date];
    12. //创建一个refreshControl对象
    13. UIRefreshControl *refreshControl = [[UIRefreshControl alloc]init];
    14. refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"下拉刷新"];
    15. [refreshControl addTarget:self action:@selector(refreshTableView) forControlEvents:UIControlEventValueChanged];
    16. //让self.refreshControl指向refreshControl
    17. self.refreshControl = refreshControl;
    18. }
    19. -(void)refreshTableView{
    20. //isRefreshing属性主要用于判断是否处于下拉刷新状态
    21. if (self.refreshControl.isRefreshing) {
    22. self.refreshControl.attributedTitle = [[NSAttributedString alloc]initWithString:@"加载中......"];
    23. //模拟获取新数据,重新获取当前时间
    24. NSDate *date = [NSDate date];
    25. [self.logs addObject:date];
    26. //模拟新数据获取完成之后,延迟2秒调用endRefreshData方法
    27. [self performSelector:@selector(endRefreshData) withObject:nil afterDelay:2];
    28. }
    29. }
    30. -(void)endRefreshData{
    31. //刷新控件结束刷新
    32. [self.refreshControl endRefreshing];
    33. //表视图更新数据
    34. [self.tableView reloadData];
    35. }
    36. -(NSInteger)tableView:(UITableView *)tableView
    37. numberOfRowsInSection:(NSInteger)section {
    38. return self.logs.count;
    39. }
    40. -(UITableViewCell *)tableView:(UITableView *)tableView
    41. cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    42. static NSString *cellIdentifer = @"Cell";
    43. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
    44. if (!cell) {
    45. cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
    46. reuseIdentifier:cellIdentifer];
    47. }
    48. NSDate *date = self.logs[indexPath.row];
    49. NSDateFormatter *df = [[NSDateFormatter alloc]init];
    50. [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    51. cell.textLabel.text = [df stringFromDate:date];
    52. return cell;
    53. }
    54. @end
     

    4 给友录添加索引条

    4.1 问题

    索引也是手机应用中经常会用到的功能,当表视图中有大量数据集合时,可以通过索引来辅助查询。本案例模拟系统通讯录,给联系人界面添加索引条,完成效果如图-11所示:

    图-11

    4.2 方案

    首先同样创建一个SingleViewApplication项目,然后创建一个带有导航的TRContactTableViewController视图控制器作为根视图控制器。定义一个NSMutableArray类型的私有属性contacts用于管理数据源,通过setter方法初始化数组,并创建一组用于给表视图展示的模拟数据。

    由于索引视图是分区显示数据的,因此需要将contacts里面存放的数据按首字母进行分组,并将每一组数据放入一个新的数组filterContacts,该数组是TRContactTableViewController类的NSMutableArray类型的私有属性。

    然后在TRContactTableViewController中实现协议方法告诉表视图需要显示的分区数、行数和显示内容,让表视图以分区形式显示数据。

    最后实现添加索引条的协议方法,根据表视图的数据添加索引条,并实现索引条和表视图的对应关系。

    4.3 步骤

    实现此案例需要按照如下步骤进行。

    步骤一:创建表视图项目,定义contacts属性管理数据源

    首先使用Xcode创建一个表视图项目,在TRContactTableViewController类中定义一个NSArray类型的私有属性contacts,通过setter方法初始化数组,并创建一组用于给表视图展示的模拟数据,代码如下所示:

     
    1. //定义contacts属性
    2. @interface TRContactTableViewController ()
    3. @property (nonatomic,strong)NSArray *contacts;
    4. @end
    5. //重写setter方法,初始化数组,创建一组模拟数据
    6. -(NSArray *)contacts {
    7. if (!_contacts) {
    8. _contacts= @[@"tarena",@"apple",@"zhangsan",@"lisi",@"wangwu",
    9. @"zhaoliu",@"chenqi",@"samsung",@"xiaomi",@"iPhone",
    10. @"iTouch,@"iPad",@"android",@"huawei",@"object-c",@"swift"];
    11. }
    12. return _contacts;
    13. }

    由于索引视图是分区显示数据的,因此需要将contacts里面存放的数据按首字母进行分组,所以需要在TRContactTableViewController类中定义一个NSMutableArray类型的私有属性filterContacts用于保存分组后的数据,代码如下所示:

     
    1. //定义filterContacts属性
    2. @interface TRContactTableViewController ()
    3. @property (nonatomic,strong)NSArray *contacts;
    4. @property (nonatomic,strong)NSMutableArray *filterContacts;
    5. @end
    6. //重写setter方法进行初始化
    7. -(NSMutableArray *)filterContacts {
    8. if (!_filterContacts) {
    9. _filterContacts = [@[]mutableCopy];
    10. }
    11. return _filterContacts;
    12. }

    然后在viewDidLoad方法中对self.contacts里面的数据按首字母进行分组并保存,代码如下所示:

     
    1. - (void)viewDidLoad {
    2. [super viewDidLoad];
    3. self.title = @"联系人";
    4. //将contacts数组数据源按首字母分组
    5. for(int i=97;i<123;i++)
    6. {
    7. //定义一个NSMutableArray类型的数组subArray,用来保存每一组的数据
    8. NSMutableArray *subArray = [@[]mutableCopy];
    9. NSString *string = [NSString stringWithFormat:@"%c",i];
    10. for(NSString *name in self.contacts)
    11. {
    12. if ([name hasPrefix:string]) {
    13. [subArray addObject:name];
    14. }
    15. }
    16. //如果subArray数组里面有元素存在将其添加到self.filterContacts中
    17. if (subArray.count) {
    18. [subArray sortUsingSelector:@selector(compare:)];
    19. [self.filterContacts addObject:subArray];
    20. }
    21. }
    22. }

    步骤二:给表视图加载数据

    首先实现协议方法numberOfSectionsInTableView:告诉tableView有多少分区,本案例的表视图的分区数就是filterContacts数组的count,代码如下所示:

    1. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    2. return self.filterContacts.count;
    3. }

    然后实现协议方法numberOfRowsInSection:告诉tableView有每个分区有多少行,代码如下所示:

    1. -(NSInteger)tableView:(UITableView *)tableView
    2. numberOfRowsInSection:(NSInteger)section {
    3. NSMutableArray *subArray = self.filterContacts[section];
    4. return subArray.count;
    5. }

    最后实现协议方法cellForRowAtIndexPath:创建cell,并设置每个cell需要显示的内容,代码如下所示:

     
    1. -(UITableViewCell *)tableView:(UITableView *)tableView
    2. cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    3. static NSString *cellIdentifier =@"Cell";
    4. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    5. if (!cell) {
    6. cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    7. }
    8. NSMutableArray *subArray = self.filterContacts[indexPath.section];
    9. cell.textLabel.text = subArray[indexPath.row];
    10. return cell;
    11. }

    运行程序,界面效果如图-12所示:

    图-12

    步骤三:给表视图添加索引条

    首先给每一个分区加上标题,分区的标题应该具有一定的代表性,代表着一组数据,并且会和索引条对应,本案例使用每组数据首字母的大写形式作为分区标题,通过协议方法titleForHeaderInSection:给分区加上标题,代码如下所示:

    1. -(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
    2. {
    3. //获取到每个分区第一个单元格显示的字符串
    4. NSMutableArray *subArray = self.filterContacts[section];
    5. NSString *name = subArray[0];
    6. //截取字符串的第一个字符,即是该分区的title
    7. NSRange range = {0,1};
    8. NSString *title = [name substringWithRange:range];
    9. return [NSString stringWithFormat:@"%@",title];
    10. }

    此时已经完成了对表视图的分区,完成界面如图-13所示:

    图-13

    接下来通过实现协议方法sectionIndexTitlesForTableView:给tableView添加索引条,该方法需要返回一个NSArray类型的数组,该数组就是索引条上显示的标题,本案例索引条上显示的标题就是分区标题,代码如下所示:

    1. -(NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView
    2. {
    3. NSMutableArray *titles=[@[]mutableCopy];
    4. //根据数据源的内容设置索引条显示的字符
    5. for(NSMutableArray *subArray in self.filterContacts)
    6. {
    7. NSString *name = subArray[0];
    8. NSRange range = {0,1};
    9. NSString *title = [name substringWithRange:range];
    10. [titles addObject: [title capitalizedString]];
    11. }
    12. return titles;
    13. }

    最后通过协议方法sectionForSectionIndexTitle:atIndex:设置索引条和表视图的对应关系,index参数就是选中索引条上的序号,本案例索引的index和表视图的section是一一对应的关系,所以直接返回index即可,代码如下所示:

    1. -(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
    2. {
    3. //点击索引条的第几个字符,表视图就显示第几个分区
    4. return index;
    5. }

    4.4 完整代码

     
    1. #import "TRContactTableViewController.h"
    2. @interface TRContactTableViewController ()
    3. @property (nonatomic,strong)NSArray *contacts;
    4. @property (nonatomic,strong)NSMutableArray *filterContacts;
    5. @end
    6. @implementation TRContactTableViewController
    7. - (void)viewDidLoad {
    8. [super viewDidLoad];
    9. self.title = @"联系人";
    10. //将contacts数组数据源按首字母分组
    11. for(int i=97;i<123;i++)
    12. {
    13. //定义一个NSMutableArray类型的数组subArray,用来保存每一组的数据
    14. NSMutableArray *subArray = [@[]mutableCopy];
    15. NSString *string = [NSString stringWithFormat:@"%c",i];
    16. for(NSString *name in self.contacts)
    17. {
    18. if ([name hasPrefix:string]) {
    19. [subArray addObject:name];
    20. }
    21. }
    22. //如果subArray数组里面有元素存在将其添加到self.filterContacts中
    23. if (subArray.count) {
    24. [subArray sortUsingSelector:@selector(compare:)];
    25. [self.filterContacts addObject:subArray];
    26. }
    27. }
    28. }
    29. -(NSArray *)contacts {
    30. if (!_contacts) {
    31. _contacts = @[@"tarena",@"apple",@"zhangsan",@"lisi",@"wangwu",@"zhaoliu",@"chenqi",@"samsung",@"xiaomi",@"iPhone",@"iTouch",@"iPad",@"android",@"huawei",@"object-c",@"swift"];
    32. }
    33. return _contacts;
    34. }
    35. -(NSMutableArray *)filterContacts {
    36. if (!_filterContacts) {
    37. _filterContacts = [@[]mutableCopy];
    38. }
    39. return _filterContacts;
    40. }
    41. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    42. return self.filterContacts.count;
    43. }
    44. -(NSInteger)tableView:(UITableView *)tableView
    45. numberOfRowsInSection:(NSInteger)section {
    46. NSMutableArray *subArray = self.filterContacts[section];
    47. return subArray.count;
    48. }
    49. -(UITableViewCell *)tableView:(UITableView *)tableView
    50. cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    51. static NSString *cellIdentifier =@"Cell";
    52. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    53. if (!cell) {
    54. cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    55. }
    56. NSMutableArray *subArray = self.filterContacts[indexPath.section];
    57. cell.textLabel.text = subArray[indexPath.row];
    58. return cell;
    59. }
    60. //设置section的title
    61. -(NSString*)tableView:(UITableView *)tableView
    62. titleForHeaderInSection:(NSInteger)section
    63. {
    64. //获取到每个分区第一个单元格显示的字符串
    65. NSMutableArray *subArray = self.filterContacts[section];
    66. NSString *name = subArray[0];
    67. //截取字符串的第一个字符,即是该分区的title
    68. NSRange range = {0,1};
    69. NSString *title = [name substringWithRange:range];
    70. return [NSString stringWithFormat:@"%@",title];
    71. }
    72. //设置索引条
    73. -(NSArray*)sectionIndexTitlesForTableView:(UITableView *)tableView
    74. {
    75. NSMutableArray *titles=[@[]mutableCopy];
    76. //根据数据源的内容设置索引条显示的字符
    77. for(NSMutableArray *subArray in self.filterContacts)
    78. {
    79. NSString *name = subArray[0];
    80. NSRange range = {0,1};
    81. NSString *title = [name substringWithRange:range];
    82. [titles addObject: [title capitalizedString]];
    83. }
    84. return titles;
    85. }
    86. //设置索引条和tableView的对应关系
    87. -(NSInteger)tableView:(UITableView *)tableView
    88. sectionForSectionIndexTitle:(NSString *)title
    89. atIndex:(NSInteger)index
    90. {
    91. //点击索引条的第几个字符,表视图就显示第几个分区
    92. return index;
    93. }
    94. @end
     

    5 行政区域选择

    5.1 问题

    本案例将学习使用tableView展示多层数据模型,实现行政区域选择功能,如图-14所示:

    图-14

    5.2 方案

    首先同样创建一个SingleViewApplication项目,然后创建一个带有导航的TRAreaTableViewController视图控制器作为根视图控制器。

    其次定义一个数据模型类TRArea,该类有两个属性一个是NSString类型的name属性用来存储地区的名字,另一个是NSMutableArray类型的subAreas用来存储子区域的信息。并且在TRArea类中定义一个静态方法demoData,用来创建一组行政区域的模拟数据,该组数据即是表视图需要展示的内容。

    然后在TRAreaTableViewController类中定义一个TRArea类型的公开属性,用于保存表视图的数据源,并在TRAppDelegate里面使用TRArea的静态方法demoData进行初始化,并且通过实现协议方法给表视图加载数据,显示区域名称;

    最后实现点击单元格推出新页面功能,推出的新页面同样是一个TRAreaTableViewController类型的对象,展示的数据是刚被点击单元格上显示区域的子区域信息(subAreas),如果子区域还存在子区域信息,还可以继续点击推出新页面。

    5.3 步骤

    实现此案例需要按照如下步骤进行。

    步骤一:创建表视图控制器和TRArea类

    首先创建一个SingleViewApplication项目,在TRAppDelegate中创建一个带有导航的TRAreaTableViewController视图控制器作为根视图控制器,代码如下所示:

     
    1. -(BOOL)application:(UIApplication *)application
    2. didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    3. {
    4. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    5. self.window.backgroundColor = [UIColor whiteColor];
    6. TRAreaTableViewController *areaTVC = [[TRAreaTableViewController alloc]initWithNibName:@"TRAreaTableViewController" bundle:nil];
    7. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:areaTVC];
    8. self.window.rootViewController = navi;
    9. [self.window makeKeyAndVisible];
    10. return YES;
    11. }

    然后创建一个TRArea类,并且该定义两个公开属性,一个是NSString类型的name属性用来存储地区的名字,另一个是NSMutableArray类型的subAreas用来存储子区域的信息,代码如下所示:

     
    1. @interface TRArea : NSObject
    2. @property (nonatomic, strong) NSString *name;
    3. @property (nonatomic, strong) NSArray *subAreas;
    4. @end

    在TRArea类中定义一个静态方法demoData,用来创建一组行政区域的模拟数据,该组数据即是表视图需要展示的内容,代码如下所示:

     
    1. + (TRArea *)demoData
    2. {
    3. TRArea *jingsong = [[TRArea alloc]init];
    4. jingsong.name = @"劲松";
    5. jingsong.subAreas = nil;
    6. TRArea *panjiayuan = [[TRArea alloc]init];
    7. panjiayuan.name = @"潘家园";
    8. panjiayuan.subAreas = nil;
    9. TRArea *chaoyang = [[TRArea alloc]init];
    10. chaoyang.name = @"朝阳";
    11. chaoyang.subAreas = [NSArray arrayWithObjects:jingsong,panjiayuan,nil];
    12. TRArea *dongcheng = [[TRArea alloc]init];
    13. dongcheng.name = @"东城";
    14. dongcheng.subAreas = nil;
    15. TRArea *haidian = [[TRArea alloc]init];
    16. haidian.name = @"海淀";
    17. haidian.subAreas = nil;
    18. TRArea *beijing = [[TRArea alloc]init];
    19. beijing.name = @"北京";
    20. beijing.subAreas = [NSArray arrayWithObjects:chaoyang,dongcheng,haidian, nil];
    21. TRArea *lujiazui = [[TRArea alloc]init];
    22. lujiazui.name = @"陆家嘴";
    23. lujiazui.subAreas = nil;
    24. TRArea *pudong = [[TRArea alloc]init];
    25. pudong.name = @"浦东";
    26. pudong.subAreas = @[lujiazui];
    27. TRArea *zhabei = [[TRArea alloc]init];
    28. zhabei.name = @"闸北";
    29. zhabei.subAreas = nil;
    30. TRArea *xuhui = [[TRArea alloc]init];
    31. xuhui.name = @"徐汇";
    32. xuhui.subAreas = nil;
    33. TRArea *shanghai = [[TRArea alloc]init];
    34. shanghai.name = @"上海";
    35. shanghai.subAreas = [NSArray arrayWithObjects:pudong,zhabei,xuhui,nil];
    36. TRArea *china = [[TRArea alloc]init];
    37. china.name = @"中国";
    38. china.subAreas = [NSArray arrayWithObjects:beijing,shanghai,nil];
    39. return china;
    40. }

    步骤二:定义TRArea类型的属性并进行初始化

    在TRAreaTableViewController类中定义一个TRArea类型的公开属性area,用于保存表视图的数据源,代码如下所示:

     
    1. @interface TRAreaTableViewController : UITableViewController
    2. @property (nonatomic, strong) TRArea *area;
    3. @end

    然后在TRAppDelegate里面使用TRArea的静态方法demoData进行对TRAreaTableViewController的area属性进行初始化,代码如下所示:

    1. -(BOOL)application:(UIApplication *)application
    2. didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    3. {
    4. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    5. self.window.backgroundColor = [UIColor whiteColor];
    6. TRAreaTableViewController *areaTVC = [[TRAreaTableViewController alloc]initWithNibName:@"TRAreaTableViewController" bundle:nil];
    7. //初始化area
    8. areaTVC.area = [TRArea demoData];
    9. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:areaTVC];
    10. self.window.rootViewController = navi;
    11. [self.window makeKeyAndVisible];
    12. return YES;
    13. }

    最后在TRAreaTableViewController类中实现协议方法,给表视图加载数据显示self.area.subAreas信息列表,代码如下所示:

     
    1. //设置表视图的行数
    2. -(NSInteger)tableView:(UITableView *)tableView
    3. numberOfRowsInSection:(NSInteger)section
    4. {
    5. return self.area.subAreas.count;
    6. }
    7. //设置表视图单元格的显示内容
    8. -(UITableViewCell *)tableView:(UITableView *)tableView
    9. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    10. {
    11. static NSString *CellIdentifier = @"Cell";
    12. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    13. if (cell == nil) {
    14. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    15. }
    16. TRArea *subarea = self.area.subAreas[indexPath.row];
    17. cell.textLabel.text = subarea.name;
    18. if(subarea.subAreas.count){
    19. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    20. }
    21. return cell;
    22. }

    步骤三:实现协议方法didSelectRowAtIndexPath:

    实现协议方法didSelectRowAtIndexPath:完成点击单元格推出一个新页面功能,这里所推出的新页面同样是一个TRAreaTableViewController类型的对象,展示的数据是被点击单元格所显示区域的subAreas属性所存储的数据,代码如下所示:

    1. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    2. {
    3. //获取被点击的区域
    4. TRArea *subArea = self.area.subAreas[indexPath.row];
    5. //如果被点击区域并没有子区域则对应单元格不能被点击
    6. if (!subArea.subAreas.count) {
    7. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    8. [cell setSelected:NO animated:YES];
    9. return;
    10. }
    11. //创建新的视图控制器对象
    12. TRAreaTableViewController *areaTVC = [[TRAreaTableViewController alloc]initWithNibName:@"TRAreaTableViewController" bundle:nil];
    13. //将被点击区域信息传递给新页面
    14. areaTVC.area = subArea;
    15. //推出新的页面
    16. [self.navigationController pushViewController:areaTVC animated:YES];
    17. }

    5.4 完整代码

    本案例中,TRAppDelegate.m文件中的完整代码如下所示:

     
    1. #import "TRAppDelegate.h"
    2. #import "TRAreaTableViewController.h"
    3. @implementation TRAppDelegate
    4. -(BOOL)application:(UIApplication *)application
    5. didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    6. {
    7. self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    8. // Override point for customization after application launch.
    9. self.window.backgroundColor = [UIColor whiteColor];
    10. TRAreaTableViewController *areaTVC = [[TRAreaTableViewController alloc]initWithNibName:@"TRAreaTableViewController" bundle:nil];
    11. //初始化area属性
    12. areaTVC.area = [TRArea demoData];
    13. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:areaTVC];
    14. self.window.rootViewController = navi;
    15. [self.window makeKeyAndVisible];
    16. return YES;
    17. }
    18. @end
     

    本案例中,TRAreaTableViewController.h文件中的完整代码如下所示

     
    1. #import<UIKit/UIKit.h>
    2. #import "TRArea.h"
    3. @interface TRAreaTableViewController : UITableViewController
    4. @property (nonatomic, strong) TRArea *area;
    5. @end
     

    本案例中,TRAreaTableViewController.m文件中的完整代码如下所示:

     
    1. #import "TRAreaTableViewController.h"
    2. @implementation TRAreaTableViewController
    3. - (void)viewDidLoad
    4. {
    5. [super viewDidLoad];
    6. self.title = self.area.name;
    7. }
    8. -(NSInteger)tableView:(UITableView *)tableView
    9. numberOfRowsInSection:(NSInteger)section
    10. {
    11. return self.area.subAreas.count;
    12. }
    13. -(UITableViewCell *)tableView:(UITableView *)tableView
    14. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    15. {
    16. static NSString *CellIdentifier = @"Cell";
    17. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    18. if (cell == nil) {
    19. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    20. }
    21. TRArea *area = self.area.subAreas[indexPath.row];
    22. cell.textLabel.text = area.name;
    23. return cell;
    24. }
    25. -(void)tableView:(UITableView *)tableView
    26. didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    27. {
    28. //获取被点击的区域
    29. TRArea *subArea = self.area.subAreas[indexPath.row];
    30. //如果被点击区域并没有子区域则对应单元格不能被点击
    31. if (!subArea.subAreas.count) {
    32. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    33. [cell setSelected:NO animated:YES];
    34. return;
    35. }
    36. //创建新的视图控制器对象
    37. TRAreaTableViewController *areaTVC = [[TRAreaTableViewController alloc]initWithNibName:@"TRAreaTableViewController" bundle:nil];
    38. //将被点击区域信息传递给新页面
    39. areaTVC.area = subArea;
    40. //推出新的页面
    41. [self.navigationController pushViewController:areaTVC animated:YES];
    42. }
    43. @end
     

    本案例中,TRArea.h文件中的完整代码如下所示

     
    1. #import<Foundation/Foundation.h>
    2. @interface TRArea : NSObject
    3. @property (nonatomic, strong) NSString *name;
    4. @property (nonatomic, strong) NSArray *subAreas;
    5. + (TRArea *)demoData;
    6. @end
     

    本案例中,TRAreaTableViewController.m文件中的完整代码如下所示:

     
    1. #import "TRArea.h"
    2. @implementation TRArea
    3. + (TRArea *)demoData
    4. {
    5. TRArea *jingsong = [[TRArea alloc]init];
    6. jingsong.name = @"劲松";
    7. jingsong.subAreas = nil;
    8. TRArea *panjiayuan = [[TRArea alloc]init];
    9. panjiayuan.name = @"潘家园";
    10. panjiayuan.subAreas = nil;
    11. TRArea *chaoyang = [[TRArea alloc]init];
    12. chaoyang.name = @"朝阳";
    13. chaoyang.subAreas = [NSArray arrayWithObjects:jingsong,panjiayuan,nil];
    14. TRArea *dongcheng = [[TRArea alloc]init];
    15. dongcheng.name = @"东城";
    16. dongcheng.subAreas = nil;
    17. TRArea *haidian = [[TRArea alloc]init];
    18. haidian.name = @"海淀";
    19. haidian.subAreas = nil;
    20. TRArea *beijing = [[TRArea alloc]init];
    21. beijing.name = @"北京";
    22. beijing.subAreas = [NSArray arrayWithObjects:chaoyang,dongcheng,haidian, nil];
    23. TRArea *lujiazui = [[TRArea alloc]init];
    24. lujiazui.name = @"陆家嘴";
    25. lujiazui.subAreas = nil;
    26. TRArea *pudong = [[TRArea alloc]init];
    27. pudong.name = @"浦东";
    28. pudong.subAreas = @[lujiazui];
    29. TRArea *zhabei = [[TRArea alloc]init];
    30. zhabei.name = @"闸北";
    31. zhabei.subAreas = nil;
    32. TRArea *xuhui = [[TRArea alloc]init];
    33. xuhui.name = @"徐汇";
    34. xuhui.subAreas = nil;
    35. TRArea *shanghai = [[TRArea alloc]init];
    36. shanghai.name = @"上海";
    37. shanghai.subAreas = [NSArray arrayWithObjects:pudong,zhabei,xuhui,nil];
    38. TRArea *china = [[TRArea alloc]init];
    39. china.name = @"中国";
    40. china.subAreas = [NSArray arrayWithObjects:beijing,shanghai,nil];
    41. return china;
    42. }
    43. @end

    6 友录中的搜索功能

    6.1 问题

    当表视图中的数据量比较大的时候,找到指定数据就会比较麻烦,因此ios提供一个搜索框控件UISearchBar,一般情况下搜索框都置于表头。本案例给通讯录的联系人界面添加搜索框,实现效果如图-15所示:

    图-15

    6.2 方案

    搜索框是一个比较复杂的控件,它有一个UISearchBarDelegate的委托协议。搜索框通常都和UISearchDisplayController配套使用,UISearchDisplayController是用来管理搜索框并显示搜索结果的视图控制器,事件处理由UISearchDisplayDelegate协议的委托对象delegate来管理。

    UISearchDisplayController除了delegate,另外还有两个委托对象searchResultsDataSource和searchResultsDelegate,分别要求遵守UITableViewDataSource协议和UITableViewDelegate协议,这两个委托对象是用来给搜索结果视图加载数据的。

    首先同样的创建一个表视图控制器的项目,表视图控制器类命名为TRContactTableViewController,该类有一个NSArray类型的属性contacts用于管理联系人数据源,重写setter方法对该属性进行初始化,并创建一组联系人的模拟数据。

    其次在TRContactTableViewController中定义一个NSMutableArray类型的私有属性filterContacts用于存储搜索之后的联系人信息,并在viewDidLoad方法里面进行赋值,当页面刚加载成功时并没有进行任何搜索,filterContacts存储的数据和contacts的数据一样。

    然后在xib文件中拖拽一个带有SearchDisplayController的SearchBar控件,将searchBar关联成TRContactTableViewController的属性searchBar。

    最后在TRContactTableViewController类中将tableHeaderView设置为searchBar,然后实现协议方法给表视图加载数据。

    6.3 步骤

    实现此案例需要按照如下步骤进行。

    步骤一:创建表视图控制器,并初始化数据源

    同以往的案例一样创建一个表视图控制类TRContactTableViewController,并且定义一个NSArray类型的属性contacts用于管理联系人数据,代码如下所示:

    1. @property (strong,nonatomic) NSArray *contacts;

    其次重写setter方法初始化contacts属性,并创建一组联系人模拟数据,代码如下所示:

     
    1. -(NSArray *)contacts {
    2. if (!_contacts) {
    3. NSArray *tempArray = @[@"tarena",@"apple",@"zhangsan",@"lisi",@"wangwu",@"zhaoliu",@"chenqi",@"samsung",@"xiaomi",@"iPhone",@"iTouch",@"iPad",@"android",@"huawei",@"object-c",@"swift"];
    4. _contacts = [tempArray sortedArrayUsingSelector:@selector(compare:)];
    5. }
    6. return _contacts;
    7. }

    然后在TRContactTableViewController中定义一个NSMutableArray类型的私有属性filterContacts用于存储搜索之后的联系人信息,并在viewDidLoad方法里面进行赋值,当页面刚加载成功时并没有进行任何搜索,filterContacts存储的数据和contacts的数据一样,代码如下所示:

     
    1. //定义属性
    2. @property (strong,nonatomic)NSMutableArray *filterContacts;
    3. //在viewDidLoad方法里面进行赋值
    4. - (void)viewDidLoad {
    5. [super viewDidLoad];
    6. self.title = @"联系人";
    7. self.filterContacts = [self.contacts mutableCopy];
    8. }

    步骤二:创建搜索框

    在xib文件中拖拽一个带有SearchDisplayController的SearchBar控件,注意这里不是UISearchBar控件,而是SearchBar and SearchDisplayController,如图-16所示:

    图-16

    这样做的好处就是可以把UISearchDisplayController也添加到搜索框,并且将委托和数据源连线完毕,如图-17所示:

    图-17

    然后searchBar关联成TRContactTableViewController的属性searchBar,代码如下所示:

     
    1. @property (weak, nonatomic) IBOutlet UISearchBar *searchBar;

    最后在TRContactTableViewController.m文件中的viewDidLoad方法里面将self.searchBar设置为tableViewHeaderView,代码如下所示:

     
    1. - (void)viewDidLoad {
    2. [super viewDidLoad];
    3. self.title = @"联系人";
    4. self.filterContacts = [self.contacts mutableCopy];
    5. self.tableView.tableHeaderView = self.searchBar;
    6. }

    步骤三:实现协议方法

    首先实现协议方法,给tableView加载数据,代码如下所示:

     
    1. -(NSInteger)tableView:(UITableView *)tableView
    2. numberOfRowsInSection:(NSInteger)section {
    3. return self.filterContacts.count;
    4. }
    5. -(UITableViewCell *)tableView:(UITableView *)tableView
    6. cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    7. static NSString *cellIdentifier = @"Cell";
    8. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    9. if (!cell) {
    10. cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    11. }
    12. cell.textLabel.text = self.filterContacts[indexPath.row];
    13. [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    14. return cell;
    15. }

    然后实现UISearchDisplayDelegate协议里面的方法searchDisplayController:shouldReloadTableForSearchString:,该方法会根据新的数据源重新给表视图加载数据,代码如下所示:

     
    1. -(BOOL)searchDisplayController:(UISearchDisplayController *)controller
    2. shouldReloadTableForSearchString:(NSString *)searchString{
    3. //根据输入的字符串筛选数据
    4. NSMutableArray *tempArray = [@[]mutableCopy];
    5. for (NSString *name in self.contacts) {
    6. if ([name hasPrefix:searchString]) {
    7. [tempArray addObject:name];
    8. }
    9. }
    10. //更新self.filterContacts存储的联系人信息
    11. self.filterContacts = tempArray;
    12. return YES;
    13. }

    最后实现UISearchBarDelegate协议的方法searchBarCancelButtonClicked:,该方法会在点击搜索框的取消按钮时被调用,本案例中点击取消即展示所有联系人信息,代码如下所示:

    1. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    2. self.filterContacts = [self.contacts mutableCopy];
    3. [self.tableView reloadData];
    4. }

    运行程序最后实现效果如图-18所示:

    图-18

    6.4 完整代码

    本案例中,TRAppDelegate.m文件中的完整代码如下所示:

     
    1. #import "TRAppDelegate.h"
    2. #import "TRSearchTableViewController.h"
    3. @implementation TRAppDelegate
    4. -(BOOL)application:(UIApplication *)application
    5. didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    6. self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    7. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:[[TRSearchTableViewController alloc]initWithNibName:@"TRSearchTableViewController" bundle:nil]];
    8. self.window.rootViewController = navi;
    9. [self.window makeKeyAndVisible];
    10. return YES;
    11. }
    12. @end
     

    本案例中,TRNewsTableViewController.h文件中的完整代码如下所示:

     
    1. #import "TRSearchTableViewController.h"
    2. @interface TRSearchTableViewController ()<UISearchBarDelegate,UISearchDisplayDelegate>
    3. @property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
    4. @property (strong,nonatomic) NSArray *contacts;
    5. @property (strong,nonatomic)NSMutableArray *filterContacts;
    6. @end
    7. @implementation TRSearchTableViewController
    8. - (void)viewDidLoad {
    9. [super viewDidLoad];
    10. self.title = @"联系人";
    11. self.tableView.tableHeaderView = self.searchBar;
    12. self.filterContacts = [self.contacts mutableCopy];
    13. }
    14. -(NSArray *)contacts {
    15. if (!_contacts) {
    16. NSArray *tempArray = @[@"tarena",@"apple",@"zhangsan",@"lisi",@"wangwu",@"zhaoliu",@"chenqi",@"samsung",@"xiaomi",@"iPhone",@"iTouch",@"iPad",@"android",@"huawei",@"object-c",@"swift"];
    17. _contacts = [tempArray sortedArrayUsingSelector:@selector(compare:)];
    18. }
    19. return _contacts;
    20. }
    21. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    22. return self.filterContacts.count;
    23. }
    24. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    25. static NSString *cellIdentifier = @"Cell";
    26. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    27. if (!cell) {
    28. cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    29. }
    30. cell.textLabel.text = self.filterContacts[indexPath.row];
    31. [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    32. return cell;
    33. }
    34. //根据输入的字符串刷新tableView
    35. - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    36. //根据输入的字符串筛选数据
    37. NSMutableArray *tempArray = [@[]mutableCopy];
    38. for (NSString *name in self.contacts) {
    39. if ([name hasPrefix:searchString]) {
    40. [tempArray addObject:name];
    41. }
    42. }
    43. //更新self.filterContacts存储的联系人信息
    44. self.filterContacts = tempArray;
    45. return YES;
    46. }
    47. //当点击searchBar的cancel按钮时退出搜索,展示所有联系人信息
    48. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    49. self.filterContacts = [self.contacts mutableCopy];
    50. [self.tableView reloadData];
    51. }
    52. @end
  • 相关阅读:
    Spring之循环依赖与解决方案
    ipv4+ipv6网络中的DDNS
    NAT、PAT、DMZ、端口映射、端口转发、UPNP
    如何实现内外网或多网络环境下上网?路由route
    局域网学习MAC地址?ping+arp
    网络故障排查?ping和trace*
    有了MAC地址,为什么还要用IP地址?
    Nginx原理解析
    磁盘io
    last总结
  • 原文地址:https://www.cnblogs.com/52190112cn/p/5049360.html
Copyright © 2011-2022 走看看