zoukankan      html  css  js  c++  java
  • 表视图控制器(TableViewController)(二)

    1 tableView的编辑模式

    1.1 问题

    表视图可以进入编辑模式,当进入编辑模式就可以进行删除、插入、移动单元等操作,本案例还是使用联系人界面学习如何进入编辑模式,以及进入编辑模式之后的删除、插入、移动等操作,如图-1所示:

    图-1

    1.2 方案

    首先还是创建一个带导航的TRContactTableViewController对象做为根视图控制器。

    其次创建一个TRContact类用于管理联系人信息,有两个NSString类型的属性分别为name和phoneNumber,本案例为了学习方便创建一组联系人信息直接使用。将创建好的联系人信息直接加载到tableView中显示。

    然后让表视图进入编辑模式,进入编辑模式的方法有两种,一种是使用导航栏的edit按钮,另一种是设置tableView的editing属性进入编辑模式。

    最后通过实现UITableViewDataSource协议的方法实现单元格的删除、插入和移动。

    1.3 步骤

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

    步骤一:创建项目,加载数据

    在已建好的Xcode项目中创建一个表视图控制器类TRContactTableViewController,并且定义一个用来管理联系人的NSMutableArray类型的公开属性contacts用来存储表视图需要展示的数据,代码如下所示:

    1. @interface TRContactTableViewController : UITableViewController
    2. @property (nonatomic, strong) NSMutableArray *contacts;
    3. @end

    其次在TRContact类里面定义两个属性name和phoneNumber,并实现一个静态方法,返回一组联系人信息,代码如下所示:

    1. //TRContact.h文件中的代码
    2. @interface TRContact : NSObject
    3. @property (nonatomic, strong) NSString *name;
    4. @property (nonatomic, strong) NSString *phoneNumber;
    5. + (NSArray *)demoData;
    6. @end
    7. //TRContact.m文件中的代码
    8. @implementation TRContact
    9. + (NSArray *)demoData
    10. {
    11. TRContact *c1 = [[TRContact alloc]init];
    12. c1.name = @"张三";
    13. c1.phoneNumber = @"18610001000";
    14. TRContact *c2 = [[TRContact alloc]init];
    15. c2.name = @"李四";
    16. c2.phoneNumber = @"18610001003";
    17. TRContact *c3 = [[TRContact alloc]init];
    18. c3.name = @"王五";
    19. c3.phoneNumber = @"18610001001";
    20. return @[c1, c2, c3];
    21. }
    22. @end

    然后让TRContactTableViewController展示联系人信息,代码如下所示:

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

    最后在TRAppDelegate的程序入口方法里面创建一个带有导航的表视图控制器做为根视图控制器,并给contactTVC的contacts属性赋值,代码如下所示:

    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. TRContactTableViewController *contactTVC = [[TRContactTableViewController alloc]initWithNibName:@"TRContactTableViewController" bundle:nil];
    7. contactTVC.contacts = [[TRContact demoData] mutableCopy];
    8. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:contactTVC];
    9. self.window.rootViewController = navi;
    10. [self.window makeKeyAndVisible];
    11. return YES;
    12. }

    步骤二:进入编辑模式

    进入编辑模式的方法有两种,一种是直接使用导航栏的edit按钮,该按钮是由系统直接提供使用,点击edit按钮能够直接进入编辑模式,再按一次就会退出编辑模式,代码如下所示:

    1. //在viewDidLoad方法里面指定导航栏的右按钮为edit按钮
    2. self.navigationItem.rightBarButtonItem = self.editButtonItem;

    另一种进入编辑模式的方式是修改tableView的editing属性,该属性是一个BOOL类型,默认值是NO,这里给导航栏添加一个左按钮,通过点击左按钮修改editing属性的值进入和退出编辑模式,代码如下所示:

    1. //viewDidLoad方法里面指定导航栏的左按钮
    2. self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editTableView:)];

    实现editTableView:方法,通过setEditing:animated:方法修改editing属性的值,根据是否进入编辑模式,按钮的标题也随着改变,代码如下所示:

    1. - (void)editTableView:(UIBarButtonItem *)button
    2. {
    3. //修改editing属性的值,进入或退出编辑模式
    4. [self.tableView setEditing:!self.tableView.editing animated:YES];
    5. if(self.tableView.editing){
    6. button.title = @"完成";
    7. }else{
    8. button.title = @"编辑";
    9. }
    10. }

    运行程序,界面完成效果如图-2所示:

    图-2

    步骤三:实现删除和插入行

    首先需要确定哪些行可以进入编辑模式,默认情况下所有行都是可以进入编辑模式的,通过实现协议方法tableView:canEditRowAtIndexPath告诉tableView,这里禁止第一行进入编辑模式,代码如下所示:

    1. -(BOOL)tableView:(UITableView *)tableView
    2. canEditRowAtIndexPath:(NSIndexPath *)indexPath
    3. {
    4. if(indexPath.row == 0) return NO;
    5. return YES;
    6. }

    然后选择编辑样式,通过实现协议方法tableView:editingStyleForRowAtIndexPath:告诉tableView编辑样式,该方法的返回值是一个UITableViewCellEditingStyle枚举类型,编辑样式只有两种删除和插入,这里让最后一行实现插入操作,其他行实现删除操作,代码如下所示:

    1. -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView
    2. editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    3. {
    4. if(indexPath.row == self.contacts.count - 1){
    5. return UITableViewCellEditingStyleInsert;
    6. }
    7. return UITableViewCellEditingStyleDelete;
    8. }

    当真正执行删除或插入某一行时,会调用协议方法tableView:commitEditingStyle: forRowAtIndexPath:,因此将删除或者插入的操作代码都写在该方法里面。

    如果执行的是删除操作则先找到该行对应的数据,其次从数据源数组中删除相应的数据对象,然后删除tableView中对应的行,删除行调用方法deleteRowsAtIndexPaths:withRowAnimation:,indexPath参数是删除行的路径,rowAnimation参数是删除行的动画样式,代码如下所示:

    1. -(void)tableView:(UITableView *)tableView
    2. commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
    3. forRowAtIndexPath:(NSIndexPath *)indexPath
    4. {
    5. if (editingStyle == UITableViewCellEditingStyleDelete) {
    6. //1. 先删除数据源中的数据
    7. [self.contacts removeObjectAtIndex:indexPath.row];
    8. //2. 再删除tableView中对应的行
    9. [tableView deleteRowsAtIndexPaths:@[indexPath]
    10. withRowAnimation:UITableViewRowAnimationFade];
    11. }
    12. }

    如果执行的是插入操作则先创建需要增加的数据对象,其次将数据对象添加到数据源数组中,然后在tableView中找到需要插入行的位置indexPath,最后调用方法insertRowsAtIndexPaths:withRowAnimation:插入行,indexPaths参数需要一个数组类型,因此将插入位置放进数组进行传递,rowAnimation参数是插入行的动画样式,代码如下所示:

    1. -(void)tableView:(UITableView *)tableView
    2. commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
    3. forRowAtIndexPath:(NSIndexPath *)indexPath
    4. {
    5. if (editingStyle == UITableViewCellEditingStyleDelete) {
    6. //1. 先删除数据源中的数据
    7. [self.contacts removeObjectAtIndex:indexPath.row];
    8. //2. 再删除tableView中对应的行
    9. [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    10. }else if (editingStyle == UITableViewCellEditingStyleInsert) {
    11. //1. 先向数据源增加数据
    12. TRContact *contact = [[TRContact alloc]init];
    13. contact.name = @"陈七";
    14. contact.phoneNumber = @"18612345678";
    15. [self.contacts addObject:contact];
    16. //2. 再向TableView增加行
    17. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.contacts.count - 1 inSection:0];
    18. [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    19. }
    20. }

    运行程序点击编辑按钮,tableView进入编辑模式,如图-3所示:

    图-3

    由图-3中可以看见,第一行被禁止编辑,第二行是删除编辑样式(红色圆圈),第三行是插入编辑样式(绿色圆圈),点击第二行前面的红圈,则在该行的尾部会出现一个Delete按钮,如图-4所示:

    图-4

    点击Delete按钮,则该行会被删除,第三行会变成第二行,如图-5所示:

    图-5

    再点击此时第二行前面的绿色按钮,则在最后一行后面直接插入一行新的单元格,显示一个新的数据,第二行的编辑样式会变成删除,如图-6所示:

    图-6

    步骤四:实现移动行

    当tableView进入编辑模式之后,默认每一行都是可以移动,每一行尾部有一个图标为三行灰色横线的按钮,就是表示该行可以移动,如图-7所示:

    图-7

    由图中可见,除了第一行,另外两行都是可以移动的,因为第一行的编辑模式被禁止了。另外还可以通过实现协议方法tableView:canMoveRowAtIndexPath:来确定哪些行可以移动,代码如下所示:

    1. -(BOOL)tableView:(UITableView *)tableView
    2. canMoveRowAtIndexPath:(NSIndexPath *)indexPath
    3. {
    4. //将第三行禁止移动
    5. if(indexPath.row == 2) return NO;
    6. return YES;
    7. }

    运行程序,可见第三行的移动按钮消失了,如图-8所示:

    图-8

    按住移动按钮则可以移动该行到任意位置,界面上显示的数据会重新排列,最后需要实现协议方法tableView:moveRowAtIndexPath: toIndexPath,将数据源数组里面的数据也进行重新排列,代码如下所示:

    1. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
    2. {
    3. TRContact *contact = self.contacts[fromIndexPath.row];
    4. [self.contacts removeObjectAtIndex:fromIndexPath.row];
    5. [self.contacts insertObject:contact atIndex:toIndexPath.row];
    6. }

    1.4 完整代码

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

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

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

     
    1. #import<UIKit/UIKit.h>
    2. @interface TRContactTableViewController : UITableViewController
    3. @property (nonatomic, strong) NSMutableArray *contacts;
    4. @end
     

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

     
    1. #import "TRContactTableViewController.h"
    2. #import "TRContact.h"
    3. @implementation TRContactTableViewController
    4. - (void)viewDidLoad
    5. {
    6. [super viewDidLoad];
    7. self.navigationItem.rightBarButtonItem = self.editButtonItem;
    8. self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editTableView:)];
    9. }
    10. - (void)editTableView:(UIBarButtonItem *)button
    11. {
    12. [self.tableView setEditing:!self.tableView.editing animated:YES];
    13. if(self.tableView.editing){
    14. button.title = @"完成";
    15. }else{
    16. button.title = @"编辑";
    17. }
    18. }
    19. -(NSInteger)tableView:(UITableView *)tableView
    20. numberOfRowsInSection:(NSInteger)section
    21. {
    22. return self.contacts.count;
    23. }
    24. -(UITableViewCell *)tableView:(UITableView *)tableView
    25. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    26. {
    27. static NSString *CellIdentifier = @"Cell";
    28. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    29. if (cell == nil) {
    30. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    31. }
    32. TRContact *contact = self.contacts[indexPath.row];
    33. cell.textLabel.text = contact.name;
    34. //cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    35. //cell.accessoryType = UITableViewCellAccessoryCheckmark;
    36. return cell;
    37. }
    38. -(BOOL)tableView:(UITableView *)tableView
    39. canEditRowAtIndexPath:(NSIndexPath *)indexPath
    40. {
    41. if(indexPath.row == 0) return NO;
    42. return YES;
    43. }
    44. -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView
    45. editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    46. {
    47. if(indexPath.row == self.contacts.count - 1) return UITableViewCellEditingStyleInsert;
    48. return UITableViewCellEditingStyleDelete;
    49. }
    50. -(void)tableView:(UITableView *)tableView
    51. commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
    52. forRowAtIndexPath:(NSIndexPath *)indexPath
    53. {
    54. if (editingStyle == UITableViewCellEditingStyleDelete) {
    55. //1. 先删除数据源中的数据
    56. [self.contacts removeObjectAtIndex:indexPath.row];
    57. //2. 再删除tableView中对应的行
    58. [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    59. }
    60. else if (editingStyle == UITableViewCellEditingStyleInsert) {
    61. //1. 先向数据源增加数据
    62. TRContact *contact = [[TRContact alloc]init];
    63. contact.name = @"陈七";
    64. contact.phoneNumber = @"18612345678";
    65. [self.contacts addObject:contact];
    66. //2. 再向TableView增加行
    67. NSIndexPath *indexPath = [NSIndexPathindexPathForRow:self.contacts.count-1 inSection:0];
    68. [tableView insertRowsAtIndexPaths:@[indexPath]
    69. withRowAnimation:UITableViewRowAnimationAutomatic];
    70. }
    71. }
    72. -(void)tableView:(UITableView *)tableView
    73. moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
    74. toIndexPath:(NSIndexPath *)toIndexPath
    75. {
    76. TRContact *contact = self.contacts[fromIndexPath.row];
    77. [self.contacts removeObjectAtIndex:fromIndexPath.row];
    78. [self.contacts insertObject:contact atIndex:toIndexPath.row];
    79. }
    80. -(BOOL)tableView:(UITableView *)tableView
    81. canMoveRowAtIndexPath:(NSIndexPath *)indexPath
    82. {
    83. if(indexPath.row == 2) return NO;
    84. return YES;
    85. }
    86. @end
     

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

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

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

     
    1. #import "TRContact.h"
    2. @implementation TRContact
    3. + (NSArray *)demoData
    4. {
    5. TRContact *c1 = [[TRContact alloc]init];
    6. c1.name = @"张三";
    7. c1.phoneNumber = @"18610001000";
    8. TRContact *c2 = [[TRContact alloc]init];
    9. c2.name = @"李四";
    10. c2.phoneNumber = @"18610001003";
    11. TRContact *c3 = [[TRContact alloc]init];
    12. c3.name = @"王五";
    13. c3.phoneNumber = @"18610001001";
    14. return @[c1, c2, c3];
    15. }
    16. @end


    2 展示4种不同的系统视图

    2.1 问题

    UITableViewCell是UIView的子类,内部由两大视图组成,内容视图contentView和辅助视图accessoryView。

    contentView由textLabel、detailTextLabel以及imageView组成。

    accessoryView默认情况下为空,在编辑模式下会隐藏起来,本案例将在上一个案例的基础上展示四种不同的辅助视图样式。

    2.2 方案

    辅助视图的类型accessoryType是一个UITableViewCellAccessoryType的枚举类型,提供了四种系统样式,分别为:

    UITableViewCellAccessoryDisclosureIndicator

    UITableViewCellAccessoryDetailDisclosureButton

    UITableViewCellAccessoryCheckmark

    UITableViewCellAccessoryDetailButton

    本案例直接在上一个案例的基础上实现,在协议方法 cellForRowAtIndexPath里面设置辅助视图的样式,查看不同的效果。

    2.3 步骤

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

    步骤一:设置辅助视图的样式

    直接在TRContactTableViewController.m文件中的协议方法tableView: cellForRowAtIndexPath里面,通过设置cell的accessoryType属性来辅助视图的样式,先设置成UITableViewCellAccessoryDisclosureIndicator样式,代码如下所示:

     
    1. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    运行程序,实现效果如图-9所示:

    图-9

    然后设置成UITableViewCellAccessoryDetailDisclosureButton样式,代码如下所示:

    1. cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;

    运行程序,实现效果如图-10所示:

    图-10

    再设置成UITableViewCellAccessoryCheckmark样式,代码如下所示:

    1. cell.accessoryType = UITableViewCellAccessoryCheckmark;

    运行程序,实现效果如图-11所示:

    图-11

    最后设置成UITableViewCellAccessoryDetailButton样式,代码如下所示:

    1. cell.accessoryType = UITableViewCellAccessoryDetailButton;

    运行程序,实现效果如图-12所示:

    图-12

    2.4 完整代码

    本案例中,TRContactTableViewController.m文件中的cellForRowAtIndexPath方法中的完整代码如下所示:

     
    1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    2. {
    3. static NSString *CellIdentifier = @"Cell";
    4. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    5. if (cell == nil) {
    6. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    7. }
    8. TRContact *contact = self.contacts[indexPath.row];
    9. cell.textLabel.text = contact.name;
    10. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    11. // cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    12. // cell.accessoryType = UITableViewCellAccessoryCheckmark;
    13. // cell.accessoryType = UITableViewCellAccessoryDetailButton;
    14. return cell;
    15. }
     

    3 展示一个Cell的不同事件方法

    3.1 问题

    上一个案例展示四种辅助视图的样式,四种样式都不同的应用场景,本案例将学习四种辅助视图的样式不同应用场景。

    3.2 方案

    UITableViewCellAccessoryDisclosureIndicator样式在界面上是一个“>”符号,通常用于提示用户点击此Cell有更详细的信息,所以使用此样式时通常都会实现协议方法tableView:didSelectRowAtIndexPath:;

    UITableViewCellAccessoryDetailDisclosureButton样式在界面上是一个“i”按钮和一个“>”符号,通常用于提示用户点击此按钮(不是Cell)会有更详细的信息,会调用协议方法tableView:accessoryButtonTappedForRowWithIndexPath:来展示详细信息,这里需要特别注意点击cell和点击i按钮调用的方法是不同的;

    UITableViewCellAccessoryCheckmark样式在界面上是一个“√”通常用于做标记;

    UITableViewCellAccessoryDetailButton样式在界面上是一个“i”按钮,通常用于提示用户点击此按钮会有详细信息,同样会通过调用协议方法tableView:accessoryButtonTappedForRowWithIndexPath:来展示消息信息。

    本案例在上一个案例的基础上通过实现协议方法didSelectRowAtIndexPath:和accessoryButtonTappedForRowWithIndexPath:来响应不同的用户选择。

    3.3 步骤

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

    步骤一:设置辅助视图样式

    本案例将辅助视图的样式设置为UITableViewCellAccessoryDetailButton,代码如下所示:

    1. cell.accessoryType = UITableViewCellAccessoryDetailButton;

    步骤二:实现点击辅助视图按钮时调用的协议方法

    点击按钮时,会自动调用UITableViewDelegate协议中的协议方法tableView:accessoryButtonTappedForRowWithIndexPath:,本案例在该方法里面输出一句话,模拟用户查看详细信息,代码如下所示:

     
    1. -(void)tableView:(UITableView *)tableView
    2. accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
    3. {
    4. TRContact *contact = self.contacts[indexPath.row];
    5. NSLog(@"用户点击的是Cell上的按钮而不是Cell本身,他可能想查看%@的详细信息", contact.name);
    6. }

    运行程序,当点击辅助视图按钮时,可见在控制台输出“用户点击的是Cell上的按钮而不是Cell本身……“,以上方法被调用。

    步骤三:实现点击cell时调用的协议方法

    点击cell时,会自动调用UITableViewDelegate协议中的协议方法tableView:didSelectRowAtIndexPath:,本案例在该方法里面输出一句话,模拟用户查看详细信息,同时将辅助视图的样式做修改,代码如下所示:

     
    1. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    2. {
    3. TRContact *contact = self.contacts[indexPath.row];
    4. NSLog(@"用户点击了此Cell本身,他想直接给%@打电话", contact.name);
    5. //1.拿到那个Cell对象
    6. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    7. //2.设置Cell的accessoryType
    8. if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
    9. cell.accessoryType = UITableViewCellAccessoryDetailButton;
    10. }else{
    11. cell.accessoryType = UITableViewCellAccessoryCheckmark;
    12. }
    13. }

    运行程序,当cell时,可见在控制台输出“用户点击了此Cell本身……”,以上方法被调用。

    3.4 完整代码

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

     
    1. #import "TRContactTableViewController.h"
    2. #import "TRContact.h"
    3. @implementation TRContactTableViewController
    4. - (void)viewDidLoad
    5. {
    6. [super viewDidLoad];
    7. self.navigationItem.rightBarButtonItem = self.editButtonItem;
    8. self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(editTableView:)];
    9. }
    10. - (void)editTableView:(UIBarButtonItem *)button
    11. {
    12. [self.tableView setEditing:!self.tableView.editing animated:YES];
    13. if(self.tableView.editing){
    14. button.title = @"完成";
    15. }else{
    16. button.title = @"编辑";
    17. }
    18. }
    19. -(NSInteger)tableView:(UITableView *)tableView
    20. numberOfRowsInSection:(NSInteger)section
    21. {
    22. return self.contacts.count;
    23. }
    24. -(UITableViewCell *)tableView:(UITableView *)tableView
    25. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    26. {
    27. static NSString *CellIdentifier = @"Cell";
    28. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    29. if (cell == nil) {
    30. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    31. }
    32. TRContact *contact = self.contacts[indexPath.row];
    33. cell.textLabel.text = contact.name;
    34. cell.accessoryType = UITableViewCellAccessoryDetailButton;
    35. return cell;
    36. }
    37. -(BOOL)tableView:(UITableView *)tableView
    38. canEditRowAtIndexPath:(NSIndexPath *)indexPath
    39. {
    40. if(indexPath.row == 0) return NO;
    41. return YES;
    42. }
    43. -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView
    44. editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
    45. {
    46. if(indexPath.row == self.contacts.count - 1) return UITableViewCellEditingStyleInsert;
    47. return UITableViewCellEditingStyleDelete;
    48. }
    49. -(void)tableView:(UITableView *)tableView
    50. commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
    51. forRowAtIndexPath:(NSIndexPath *)indexPath
    52. {
    53. if (editingStyle == UITableViewCellEditingStyleDelete) {
    54. //1. 先删除数据源中的数据
    55. [self.contacts removeObjectAtIndex:indexPath.row];
    56. //2. 再删除tableView中对应的行
    57. [tableView deleteRowsAtIndexPaths:@[indexPath]
    58. withRowAnimation:UITableViewRowAnimationFade];
    59. }
    60. else if (editingStyle == UITableViewCellEditingStyleInsert) {
    61. //1. 先向数据源增加数据
    62. TRContact *contact = [[TRContact alloc]init];
    63. contact.name = @"陈七";
    64. contact.phoneNumber = @"18612345678";
    65. [self.contacts addObject:contact];
    66. //2. 再向TableView增加行
    67. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.contacts.count - 1 inSection:0];
    68. [tableView insertRowsAtIndexPaths:@[indexPath]
    69. withRowAnimation:UITableViewRowAnimationAutomatic];
    70. }
    71. }
    72. -(void)tableView:(UITableView *)tableView
    73. moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
    74. toIndexPath:(NSIndexPath *)toIndexPath
    75. {
    76. TRContact *contact = self.contacts[fromIndexPath.row];
    77. [self.contacts removeObjectAtIndex:fromIndexPath.row];
    78. [self.contacts insertObject:contact atIndex:toIndexPath.row];
    79. }
    80. -(BOOL)tableView:(UITableView *)tableView
    81. canMoveRowAtIndexPath:(NSIndexPath *)indexPath
    82. {
    83. if(indexPath.row == 2) return NO;
    84. return YES;
    85. }
    86. #pragma mark - Table view delegate
    87. -(void)tableView:(UITableView *)tableView
    88. didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    89. {
    90. TRContact *contact = self.contacts[indexPath.row];
    91. NSLog(@"用户点击了此Cell本身,他想直接给%@打电话", contact.name);
    92. //1.拿到那个Cell对象
    93. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    94. //2.设置Cell的accessoryType
    95. if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
    96. cell.accessoryType = UITableViewCellAccessoryDetailButton;
    97. }else{
    98. cell.accessoryType = UITableViewCellAccessoryCheckmark;
    99. }
    100. }
    101. -(void)tableView:(UITableView *)tableView
    102. accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
    103. {
    104. TRContact *contact = self.contacts[indexPath.row];
    105. NSLog(@"用户点击的是Cell上的按钮而不是Cell本身,他可能想查看%@的详细信息", contact.name);
    106. }
    107. @end
     

    4 展示自定义辅助视图

    4.1 问题

    辅助视图除了可以使用系统提供的四种样式,还可以自定义辅助视图根据不同需求展示不同的界面,本案例将学习如何自定义辅助视图,如图-13所示:

    图-13

    4.2 方案

    首先自定义一个视图,根据不同的需求展示不同的界面,然后让cell.accessoryView指向自定义的视图即可。

    4.3 步骤

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

    步骤一:创建表视图项目

    首先使用Xcode创建一个表视图项目,在TRMyTableViewController.m文件中实现协议方法告诉tableView展示多少分区和多少行,本案例展示两个分区,第一个分区有两行单元格,第二个分区有三行单元格,代码如下所示:

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

    然后在cellForRowAtIndexPath:方法里面创建cell,代码如下所示:

     
    1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    2. {
    3. static NSString *CellIdentifier = @"Cell";
    4. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    5. if (cell == nil) {
    6. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    7. return cell;
    8. }

    步骤二:自定义辅助视图

    本案例中让表视图的每一行展示几种不同的自定义辅助视图,所以根据每个cell不同的路径显示不一样的辅助视图,首先自定义第一个分区第一行单元格的辅助视图,展示一个UISwitch开关,代码如下所示:

     
    1. if(indexPath.section==0 && indexPath.row==0){
    2. cell.textLabel.text = @"蓝牙";
    3. //自定义辅助视图,创建一个UISwitch对象
    4. UISwitch *blueSwitch = [[UISwitch alloc]init];
    5. //cell.accessoryView指向自定义视图
    6. cell.accessoryView = blueSwitch;
    7. }

    然后自定义第一个分区第二行单元格的辅助视图,展示一个UIButton按钮,代码如下所示:

     
    1. if(indexPath.section==0 && indexPath.row==0){
    2. cell.textLabel.text = @"蓝牙";
    3. UISwitch *blueSwitch = [[UISwitch alloc]init];
    4. cell.accessoryView = blueSwitch;
    5. }else if(indexPath.section==0 && indexPath.row==1){
    6. cell.textLabel.text = @"运营商";
    7. //自定义辅助视图,创建一个UIButton对象
    8. UIButton *serviceButton = [UIButton buttonWithType:UIButtonTypeSystem];
    9. serviceButton.frame = CGRectMake(0, 0, 44, 44);
    10. [serviceButton setTitle:@"选择" forState:UIControlStateNormal];
    11. [serviceButton addTarget:self
    12. action:@selector(selectService:)
    13. forControlEvents:UIControlEventTouchUpInside];
    14. //cell.accessoryView指向自定义视图
    15. cell.accessoryView = serviceButton;
    16. }

    第一个分区的辅助视图就定义完成了,运行程序,展示界面效果如图-14所示:

    图-14

    然后再自定义第二个分区的辅助视图,第一行单元格的辅助视图展示一个UITextField文本输入框,代码如下所示:

     
    1. if(indexPath.section==1 && indexPath.row==0){
    2. cell.textLabel.text = @"姓名:";
    3.          //自定义辅助视图,创建一个UITextField对象
    4. UITextField *inputBox = [[UITextField alloc]initWithFrame:CGRectMake(0, 2, 200, 35)];
    5. [inputBox setBackgroundColor:[UIColor lightGrayColor]];
    6. //cell.accessoryView指向自定义视图
    7. cell.accessoryView = inputBox;
    8. }

    最后自定义第二个分区第二行单元格的辅助视图,展示一个UILabel和一个UIStepper控件,代码如下所示:

     
    1. if(indexPath.section==1 && indexPath.row==0){
    2. cell.textLabel.text = @"姓名:";
    3. UITextField *inputBox = [[UITextField alloc]initWithFrame:CGRectMake(0, 2, 200, 35)];
    4. [inputBox setBackgroundColor:[UIColor lightGrayColor]];
    5. cell.accessoryView = inputBox;
    6. }elseif(indexPath.section==1 &&indexPath.row==1){
    7. cell.textLabel.text = @"次数:";
    8. //自定义辅助视图,创建一个UIView对象
    9. UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 44)];
    10. //创建一个UILabel对象
    11. UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, 20, 34)];
    12. label.text = @"0";
    13. label.textAlignment = NSTextAlignmentCenter;
    14. //创建一个UIStepper对象
    15. UIStepper *stepper = [[UIStepper alloc]initWithFrame:CGRectMake(80, 5, 160, 34)];
    16. //将创建的label和stepper添加到父试图
    17. [view addSubview:label];
    18. [view addSubview:stepper];
    19. //cell.accessoryView指向自定义视图
    20. cell.accessoryView = view;
    21. }else{
    22. cell.textLabel.text = @"hello.....";
    23. }

    第二个分区的辅助视图就定义完成了,运行程序,展示界面效果如图-15所示:

    图-15

    4.4 完整代码

    5 自定义ContentView的内容,展示当前计算机语言排名

    5.1 问题

    上一个案例学习了如何自定义辅助视图,本案例将学习如何自定义内容视图contentView,展示TIOBE计算机语言排行榜,如图-16所示:

    图-16

    5.2 方案

    contentView中的子视图有三个textLabel,detailTextLabel和imageView,如果不进行赋值,这三个子视图都是nil。

    这三个子视图都可以进行自定义,步骤如下:

    首先根据不同的界面需求分别自定义textLabel,detailTextLabel和imageView;

    然后分别将自定义好的三个子视图添加到contentView中即可。

    5.3 步骤

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

    步骤一:创建表视图项目

    首先使用Xcode创建一个表视图项目,在TRLanguageTableViewController.m文件中定义一个用于保存数据源的NSArray类型的属性,并且实现协议方法告诉tableView展示多少行,代码如下所示:

    1. //定义保存数据源的属性
    2. @interface TRLanguageTableViewController ()
    3. @property (nonatomic, strong) NSArray *language;
    4. @end
    5. //初始化数组
    6. - (NSArray *)language
    7. {
    8. return @[@"C", @"Java", @"Objective-C", @"C++", @"C#", @"Basic", @"PHP", @"Python", @"Javascript", @"VB.Net", @"Transact-SQL", @"Perl", @"Ruby", @"ActionScript", @"F#", @"Lisp", @"Delphi/Pascal"];
    9. }
    10. //实现协议方法告诉tableView显示多少行
    11. -(NSInteger)tableView:(UITableView *)tableView
    12. numberOfRowsInSection:(NSInteger)section
    13. {
    14. }

    步骤二:创建cell,并且自定义contentView

    在协议方法cellForRowAtIndexPath:里面创建cell对象,代码如下所示:

     
    1. -(UITableViewCell *)tableView:(UITableView *)tableView
    2. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    3. {
    4. static NSString *CellIdentifier = @"Cell";
    5. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    6. if (cell == nil) {
    7. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    8. }
    9. return cell;
    10. }

    然后在以上方法中自定义cell的内容视图,由于cell是重用的,所以只用在第一次新创建cell对象的时候自定义好contentView即可,也就是将自定义内容视图的相关代码写在if(cell==nil)判断语句里面。

    本案例的contentView里面是一个自定义的UILabel对象,由于每一行UILabel对象显示的文本内容不同,所以UILabel对象的定义应该在if(cell==nil)判断语句的前面,UILabel对象的创建(获取)和样式设置在if(cell==nil)判断语句里面,if(cell==nil)判断语句后面才是UILabel对象text属性的设置,代码如下所示:

     
    1. -(UITableViewCell *)tableView:(UITableView *)tableView
    2. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    3. {
    4. static NSString *CellIdentifier = @"Cell";
    5. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    6. //定义UILabel类型的变量,但是此时并不需要创建对象
    7. UILabel *label = nil;
    8. if (cell == nil) {
    9. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    10. //在第一次新创建cell对象时,创建UILabel对象
    11. label = [[UILabel alloc]init];
    12. //设置label的位置大小
    13. label.frame = CGRectMake(0, 0, 320, 44);
    14. //设置label的字体颜色
    15. label.textColor = [UIColor lightGrayColor];
    16. //设置label的字体大小和字体样式
    17. label.font = [UIFont italicSystemFontOfSize:18];
    18. //设置label的文本对齐样式
    19. label.textAlignment = NSTextAlignmentCenter;
    20. //设置label的字体阴影
    21. label.shadowColor = [UIColor blackColor];
    22. label.shadowOffset = CGSizeMake(1, 1);
    23. //将label添加到contentView中
    24. [cell.contentView addSubview:label];
    25. //设置label的tag值
    26. label.tag = 1;
    27. }else {
    28. //当获取到可重用的cell时,通过tag值得到label对象
    29. label = (UILabel*)[cell.contentView viewWithTag:1];
    30. }
    31. //设置label的显示内容
    32. label.text = self.language[indexPath.row];
    33. return cell;
    34. }

    5.4 完整代码

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

     
    1. #import "TRLanguageTableViewController.h"
    2. @interface TRLanguageTableViewController ()
    3. @property (nonatomic, strong) NSArray *language;
    4. @end
    5. @implementation TRLanguageTableViewController
    6. - (NSArray *)language
    7. {
    8. return @[@"C", @"Java", @"Objective-C", @"C++", @"C#", @"Basic", @"PHP", @"Python", @"Javascript", @"VB.Net", @"Transact-SQL", @"Perl", @"Ruby", @"ActionScript", @"F#", @"Lisp", @"Delphi/Pascal"];
    9. }
    10. - (void)viewDidLoad
    11. {
    12. [super viewDidLoad];
    13. self.title = @"TIOBE";
    14. }
    15. -(NSInteger)tableView:(UITableView *)tableView
    16. numberOfRowsInSection:(NSInteger)section
    17. {
    18. return self.language.count;
    19. }
    20. -(UITableViewCell *)tableView:(UITableView *)tableView
    21. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    22. {
    23. static NSString *CellIdentifier = @"Cell";
    24. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    25. UILabel *label = nil;
    26. if (cell == nil) {
    27. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    28. label = [[UILabel alloc]init];
    29. label.frame = CGRectMake(0, 0, 320, 44);
    30. label.textColor = [UIColor lightGrayColor];
    31. label.font = [UIFont italicSystemFontOfSize:18];
    32. label.textAlignment = NSTextAlignmentCenter;
    33. //设置阴影
    34. label.shadowColor = [UIColor blackColor];
    35. label.shadowOffset = CGSizeMake(1, 1);
    36. [cell.contentView addSubview:label];
    37. label.tag = 1;
    38. }else {
    39. label = (UILabel*)[cell.contentView viewWithTag:1];
    40. }
    41. label.text = self.language[indexPath.row];
    42. return cell;
    43. }
    44. @end
     

    6 网易新闻项目的Cell自定义

    6.1 问题

    UITableViewCell类是表视图的标准Cell类,自定义Cell就是自己写一个Cell类继承至UITabelViewCell,然后在协议方法cellForRowAtIndexPath:里面创建cell对象时使用自定义的Cell类型并返回。

    本案例将使用自定义cell的方式模拟实现一个网易新闻客户端的界面,实现效果如图-17所示:

    图-17

    6.2 方案

    首先创建一个表视图控制器的项目,表视图控制器类命名为TRNewsTableViewController,该类有一个管理新闻数据的NSArray类型的属性news。

    其次根据本案例的需求创建一个实体新闻类TRNews类,该类有四个属性分别为NSString类型的title(新闻标题)、NSString类型的content(新闻内容),NSUInteger类型的count(评论数)以及NSString类型的imageName(新闻图片名称),本案例中在该类中直接定义一个静态方法,用于创建一组新闻数据。在TRAppDelegate.m文件中使用该静态方法给TRNewsTableViewController的news属性赋值。

    然后创建一个带有xib的TRNewsCell类,继承至UITabelViewCell,在xib文件中根据需要从对象库中拖放控件,本案例拖放一个UIImageView和三个UILabel对象。

    最后在TRNewsTableViewController.m文件中实现协议方法,创建自定义类型的cell,并加载数据。

    6.3 步骤

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

    步骤一:创建TRNewsTableViewController类

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

    1. @interface TRNewsTableViewController : UITableViewController
    2. @property (nonatomic, strong) NSArray *news;
    3. @end

    然后将本案例所需的图片素材拖放进项目。

    步骤二:创建新闻实体类TRNews

    创建一个TRNews类继承至NSObject,并且定义四个属性分别为NSString类型的title(新闻标题)、NSString类型的content(新闻内容),NSUInteger类型的count(评论数)以及NSString类型的imageName(新闻图片名称),代码如下所示:

    1. @interface TRNews : NSObject
    2. @property (nonatomic, strong) NSString *title;
    3. @property (nonatomic, strong) NSString *content;
    4. @property (nonatomic) NSUInteger count;
    5. @property (nonatomic, strong) NSString *imageName;
    6. @end

    然后定义一个静态方法用于返回一组新闻数据,代码如下所示:

     
    1. + (NSArray *)demoData
    2. {
    3. TRNews *n1 = [[TRNews alloc]init];
    4. n1.title = @"四川青川县今晨发生4.8地震";
    5. n1.content = @"震源深度15千米;网友反映称成都、绵阳等地均有震感";
    6. n1.count = 2255;
    7. n1.imageName = @"Apple Tree.ico";
    8. TRNews *n2 = [[TRNews alloc]init];
    9. n2.title = @"2名夺刀少年遭多所高校"哄抢"";
    10. n2.content = @"继南昌大学、清华大学、北京理工大学与澳门科技大学加入";
    11. n2.count = 8000;
    12. n2.imageName = @"Bliss.ico";
    13. TRNews *n3 = [[TRNews alloc]init];
    14. n3.title = @"代码显示iOS8将可分屏多任务";
    15. n3.content = @"开发者:该代码支持利用1/2,1/4或3/4屏幕来显示应用";
    16. n3.count = 8000;
    17. n3.imageName = @"Flowers.ico";
    18. TRNews *n4 = [[TRNews alloc]init];
    19. n4.title = @"Swift语言估计下月进入TIOBE前20名";
    20. n4.content = @"据上市公司达内科技估计,2014年7月世界计算面语言排名中,Swift将出现在前20名";
    21. n4.count = 12000000;
    22. n4.imageName = @"Rain.ico";
    23. return @[n1, n2, n3, n4];
    24. }

    最后在TRAppDelegate.m文件的程序入口方法里面给TRNewsTableViewController的news属性赋值,代码如下所示:

     
    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. TRNewsTableViewController *newsTVC = [[TRNewsTableViewController alloc]initWithNibName:@"TRNewsTableViewController" bundle:nil];
    7. //给newsTVC的news属性赋值
    8. newsTVC.news = [TRNews demoData];
    9. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:newsTVC];
    10. self.window.rootViewController = navi;
    11. [self.window makeKeyAndVisible];
    12. return YES;
    13. }

    步骤三:创建TRNewsCell类

    创建一个带有xib文件的TRNewsCell类,该类继承至UITableViewCell,如图-18所示:

    图-18

    然后选中xib文件,在右边栏的第五个检查器中将cell的高度设置为74,如图-19所示:

    图-19

    在xib界面上根据需求从对象库中拖放控件到contentView上,本案例拖放一个UIImageView对象用于显示新闻图片,在拖放三个UILabel对象分别用于显示新闻标题、新闻内容以及新闻评论数,xib界面效果如图-20所示:

    图-20

    最后以拉线的方式将xib中的各控件关联成TRNewsCell的公开属性,代码如下所示:

    1. @interface TRNewsCell : UITableViewCell
    2. @property (weak, nonatomic) IBOutlet UILabel *titleLabel;
    3. @property (weak, nonatomic) IBOutlet UILabel *contentLabel;
    4. @property (weak, nonatomic) IBOutlet UILabel *countLabel;
    5. @property (weak, nonatomic) IBOutlet UIImageView *newsImageView;
    6. @end

    步骤四:在TRNewsTableViewController中使用自定义cell

    首先通过协议方法numberOfRowsInSection:告诉表视图需要显示的行数,代码如下所示:

    1. -(NSInteger)tableView:(UITableView *)tableView
    2. numberOfRowsInSection:(NSInteger)section
    3. {
    4. return self.news.count;
    5. }

    然后先将自定义的TRNewsCell类进行注册,注册首先需要定义一个static类型的标示符,然后在viewDidLoad方法里面使用registerNib:forCellReuseIdentifier:进行注册,代码如下所示:

    1. //定义一个注册标识
    2. static NSString *cellIdentifier = @"NewsCell";
    3. - (void)viewDidLoad
    4. {
    5. [super viewDidLoad];
    6. self.title = @"网易新闻客户端";
    7. //注册cell
    8. UINib *nib = [UINib nibWithNibName:@"TRNewsCell" bundle:nil];
    9. [self.tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
    10. }

    最后在协议方法cellForRowAtIndexPath:方法里面创建自定义的TRNewsCell类型的对象cell,并对cell各属性进行赋值,当然不要忘记导入头文件TRNewsCell.h,代码如下所示:

     
    1. -(UITableViewCell *)tableView:(UITableView *)tableView
    2. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    3. {
    4. TRNews *news = self.news[indexPath.row];
    5. //创建自定义的TRNewsCell类型的对象cell
    6. TRNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    7. //设置cell的titleLabel显示的内容
    8. cell.titleLabel.text = news.title;
    9. //设置cell的contentLabel显示的内容
    10. cell.contentLabel.text = news.content;
    11. //设置cell的countLabel显示的内容
    12. int x = news.count / 10000;
    13. cell.countLabel.text = [NSString stringWithFormat:@"跟帖:%i%@", x?x:news.count, x?@"万":@""];
    14. //设置cell的newsImageView显示的图片
    15. cell.newsImageView.image = [UIImage imageNamed:news.imageName];
    16. return cell;
    17. }

    本案例中还需通过协议方法要告诉tableView每一行的显示高度,因为此时已经不再是默认的单元格高度,代码如下所示:

     
    1. -(CGFloat)tableView:(UITableView *)tableView
    2. heightForRowAtIndexPath:(NSIndexPath *)indexPath
    3. {
    4. return 76;
    5. }

    6.4 完整代码

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

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

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

     
    1. #import<UIKit/UIKit.h>
    2. @interface TRNewsTableViewController : UITableViewController
    3. @property (nonatomic, strong) NSArray *news;
    4. @end
     

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

     
    1. #import "TRNewsTableViewController.h"
    2. #import "TRNews.h"
    3. #import "TRNewsCell.h"
    4. @implementation TRNewsTableViewController
    5. static NSString *cellIdentifier = @"NewsCell";
    6. - (void)viewDidLoad
    7. {
    8. [super viewDidLoad];
    9. self.title = @"网易新闻客户端";
    10. UINib *nib = [UINib nibWithNibName:@"TRNewsCell" bundle:nil];
    11. [self.tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
    12. }
    13. -(NSInteger)tableView:(UITableView *)tableView
    14. numberOfRowsInSection:(NSInteger)section
    15. {
    16. return self.news.count;
    17. }
    18. -(UITableViewCell *)tableView:(UITableView *)tableView
    19. cellForRowAtIndexPath:(NSIndexPath *)indexPath
    20. {
    21. TRNews *news = self.news[indexPath.row];
    22. TRNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    23. cell.titleLabel.text = news.title;
    24. cell.contentLabel.text = news.content;
    25. int x = news.count / 10000;
    26. cell.countLabel.text = [NSString stringWithFormat:@"跟帖:%i%@", x?x:news.count, x?@"万":@""];
    27. cell.newsImageView.image = [UIImage imageNamed:news.imageName];
    28. return cell;
    29. }
    30. -(CGFloat)tableView:(UITableView *)tableView
    31. heightForRowAtIndexPath:(NSIndexPath *)indexPath
    32. {
    33. return 76;
    34. }
    35. @end
     

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

     
    1. #import<UIKit/UIKit.h>
    2. @interface TRNewsCell : UITableViewCell
    3. @property (weak, nonatomic) IBOutlet UILabel *titleLabel;
    4. @property (weak, nonatomic) IBOutlet UILabel *contentLabel;
    5. @property (weak, nonatomic) IBOutlet UILabel *countLabel;
    6. @property (weak, nonatomic) IBOutlet UIImageView *newsImageView;
    7. @end
     

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

     
    1. #import<Foundation/Foundation.h>
    2. @interface TRNews : NSObject
    3. @property (nonatomic, strong) NSString *title;
    4. @property (nonatomic, strong) NSString *content;
    5. @property (nonatomic) NSUInteger count;
    6. @property (nonatomic, strong) NSString *imageName;
    7. + (NSArray *)demoData;
    8. @end

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

     
    1. #import "TRNews.h"
    2. @implementation TRNews
    3. + (NSArray *)demoData
    4. {
    5. TRNews *n1 = [[TRNews alloc]init];
    6. n1.title = @"四川青川县今晨发生4.8地震";
    7. n1.content = @"震源深度15千米;网友反映称成都、绵阳等地均有震感";
    8. n1.count = 2255;
    9. n1.imageName = @"Apple Tree.ico";
    10. TRNews *n2 = [[TRNews alloc]init];
    11. n2.title = @"2名夺刀少年遭多所高校"哄抢"";
    12. n2.content = @"继南昌大学、清华大学、北京理工大学与澳门科技大学加入";
    13. n2.count = 8000;
    14. n2.imageName = @"Bliss.ico";
    15. TRNews *n3 = [[TRNews alloc]init];
    16. n3.title = @"代码显示iOS8将可分屏多任务";
    17. n3.content = @"开发者:该代码支持利用1/2,1/4或3/4屏幕来显示应用";
    18. n3.count = 8000;
    19. n3.imageName = @"Flowers.ico";
    20. TRNews *n4 = [[TRNews alloc]init];
    21. n4.title = @"Swift语言估计下月进入TIOBE前20名";
    22. n4.content = @"据上市公司达内科技估计,2014年7月世界计算面语言排名中,Swift将出现在前20名";
    23. n4.count = 12000000;
    24. n4.imageName = @"Rain.ico";
    25. return @[n1, n2, n3, n4];
    26. }
    27. @end
  • 相关阅读:
    LR: Voxel Map for Visual SLAM
    LR A Simplified Active Calibration Algorithm for Focal Length Estimation
    # LiteratureReview LeGO-LOAM
    Literature Review: Road is Enough
    vue使用SockJS实现webSocket通信
    flex布局常用样式
    vue 关于render渲染函数的使用
    vue单页面应用打开新窗口显示跳转页面的方法
    vuex项目框架
    动态form表单,数据编辑部分数据编辑输入视图不更新问题
  • 原文地址:https://www.cnblogs.com/52190112cn/p/5049347.html
Copyright © 2011-2022 走看看