表視圖控制器(TableViewController)(一)


1 創建一個UITableViewController並展示簡單數據

1.1 問題

有很多移動客戶端的應用都是采用表的形式來展示數據,因為表視圖能使數據看起來更規整、更有調理,比如微信界面就是使用的表視圖,如圖-1所示:

圖-1

在IOS中表視圖是非常重要的視圖,類型名稱為UITabelViewController,是UIViewController的子類,本案例將學習如何使用UITableViewController來展示簡單的數據,完成效果如圖-2所示:

圖-2

1.2 方案

首先創建一個SingleViewApplication項目,創建一個TRMyTableViewController類繼承至UITableViewController,在TRAppDelegate的程序入口方法里面創建一個TRMyTableViewController對象做為根視圖控制器。

UITableViewController類有一個UITabelView類型的屬性tableView,該屬性就是表視圖控制器管理的表視圖,類似UIViewController和屬性view的關系。表視圖由以下幾個部分組成:

表頭視圖tableHeaderView:表視圖最上邊的視圖,用於展示表視圖的信息;

表腳視圖tableFooterView:表視圖最下邊的視圖;

單元格cell:是一個UITableViewCell對象,表視圖每一行的單位視圖;

分區section:由多個單元格cell組成,有分區頭和分區腳。

表視圖有兩個委托協議一個是UITableViewDataSource用於給表視圖加載數據,另一個是UITableViewDelegate用於實現其他事件的委托。

另外表視圖還有兩個屬性id <UITableViewDataSource>類型的dataSource和id <UITableViewDelegate>類型的delegate,分別用於指定加載數據的對象和被委托對象。

然后在TRMyTableViewController類里面通過實現的UITableViewDataSource協議的方法給表視圖加載簡單的數據。

1.3 步驟

實現此案例需要按照如下步驟進行。

步驟一:創建TRMyTableViewController對象做為程序的根視圖控制器

首先創建一個單視圖應用項目命名為TRMyTableViewController,再創建一個帶有xib的TRMyTableViewController類繼承至UITableViewController,生成的xib文件如圖-3所示:

圖-3

然后在TRAppDelegate.m的程序入口方法中創建一個TRMyTableViewController對象做為程序的根視圖,代碼如下所示:

 
  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. //創建一個TRTableViewController對象做為根視圖控制器
  7. TRMyTableViewController *myTVC = [[TRMyTableViewController alloc]initWithNibName:@"TRMyTableViewController" bundle:nil];
  8. self.window.rootViewController = myTVC;
  9. [self.window makeKeyAndVisible];
  10. return YES;
  11. }

在這里myTVC視圖控制器對象管理的表視圖就是程序展示的第一個界面視圖。

步驟二:實現UITableViewDataSource協議的方法給表視圖加載數據

UITabelViewController類遵守了兩個協議一個是UITableViewDataSource用於給表視圖加載數據,另一個是UITableViewDelegate用於實現委托,這里先學習通過實現UITableViewDataSource協議的方法來給表視圖加載數據。

系統會自動將TRMyTableViewController指定為它所管理的的表視圖的dataSource和delegate,可以在xib中查看,選中tableView點擊右鍵,出現如圖-4所示的窗口:

圖-4

從圖可見dataSource和delegate都是和File’s Owner關聯上的,此時的File’s Owner即TRMyTableViewController。

TRMyTableViewController類是UITabelViewController的子類,所以TRMyTableViewController也遵守了以上兩個協議,不用再額外寫遵守協議代碼,直接實現協議里面的方法即可,這里需要實現如下三個協議方法:

numberOfSectionsInTableView:可選方法,用於告訴表視圖需要顯示多少分區,不實現的時候默認返回1個分區;

tableView:numberOfRowsInSection:必須實現的方法,用於告訴表視圖每組需要顯示多少行;

tableView:cellForRowAtIndexPath:必須實現的方法,用於告訴表視圖每一行顯示的內容;

在這里先指定表視圖顯示1組,每組顯示20行,代碼如下所示:

  1. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  2. {
  3. return 1;
  4. }
  5. -(NSInteger)tableView:(UITableView *)tableView
  6. numberOfRowsInSection:(NSInteger)section
  7. {
  8. return 20;
  9. }

每一行用於顯示內容的是一個UITableViewCell類型的對象,該方法里面需要先創建一個UITableViewCell類型的對象cell,使用初始化方法initWithStyle: reuseIdentifier:進行初始化,style參數是cell的樣式,這里選擇系統默認的樣式即可,reuseIdentifier參數傳遞一個字符串@”Cell”,本案例先不對該參數的作用進行闡述,后面的案例會進行解釋。

UITableViewCell有一個UILabel類型的屬性textLabel,該屬性用來展示文本內容,這里設置cell的textLabel的顯示內容,最后將cell對象返回,代碼如下所示:

 
  1. -(UITableViewCell *)tableView:(UITableView *)tableView
  2. cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3. {
  4. //創建cell對象
  5. UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
  6. //設置cell的顯示內容
  7. cell.textLabel.text = @"Hello World.";
  8. return cell;
  9. }

1.4 完整代碼

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

 
  1. #import "TRAppDelegate.h"
  2. #import "TRMyTableViewController.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. TRMyTableViewController *myTVC = [[TRMyTableViewController alloc]initWithNibName:@"TRMyTableViewController" bundle:nil];
  10. self.window.rootViewController = myTVC;
  11. [self.window makeKeyAndVisible];
  12. return YES;
  13. }
  14. @end

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

 
  1. #import "TRMyTableViewController.h"
  2. @implementation TRMyTableViewController
  3. #pragma mark - Table view data source
  4. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  5. {
  6. return 1;
  7. }
  8. -(NSInteger)tableView:(UITableView *)tableView
  9. numberOfRowsInSection:(NSInteger)section
  10. {
  11. return 20;
  12. }
  13. -(UITableViewCell *)tableView:(UITableView *)tableView
  14. cellForRowAtIndexPath:(NSIndexPath *)indexPath
  15. {
  16. UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
  17. cell.textLabel.text = @"Hello World.";
  18. return cell;
  19. }
  20. @end
 

2 使用IndexPath中的兩個屬性區別分區展示數據

2.1 問題

上一個案例已經學習了如何使用表視圖控制器展現一組簡單的數據,本案例將在上一個案例的基礎上讓表視圖以多個分區的形式展示數據,如圖-5所示:

圖-5

2.2 方案

首先同上一個案例一樣創建一個表視圖控制器TRMytableViewController作為本應用的根視圖控制器。

其次通過實現UITableViewDataSource協議的方法告訴tableView有多少分區、有多少行以及每一行的顯示內容。

2.3 步驟

實現此案例需要按照如下步驟進行。

步驟一:創建TRMyTableViewController對象做為程序的根視圖控制器

首先同第一個案例一樣創建一個單視圖應用項目命名為TRMyTableViewController,再創建一個帶有xib的TRMyTableViewController類繼承至UITableViewController。

步驟二:實現UITableViewDataSource協議的方法給表視圖加載數據

NSIndexPath用來管理存儲路徑,有兩個屬性section和row,section用來描述分區,row用來描述分區里面的某一行。

首先通過實現numberOfSectionsInTableView:方法讓tabelView分成三個區,該方法不實現默認是返回一個分區,代碼如下所示:

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

然后通過tableView:numberOfRowsInSection:方法確定每個分區的行數,代碼如下所示:

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

最后通過實現tableView:cellForRowAtIndexPath:確定不同分區的每一行的顯示內容,本案例創建cell選擇的是UITableViewCellStyleSubtitl類型,該類型除了顯示textLabel的顯示內容,還可以設置cell的另外兩個屬性,如下所示:

imageView屬性:用來顯示一張圖片;

detailTextLabel屬性:用來顯示詳細信息。

代碼如下所示:

 
  1. -(UITableViewCell *)tableView:(UITableView *)tableView
  2. cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3. {
  4. UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
  5. if(indexPath.section == 0){
  6. cell.textLabel.text = [NSString stringWithFormat:@"第0區的第%d行",indexPath.row];
  7. }else{
  8. cell.textLabel.text = [NSString stringWithFormat:@"%d區%d行",indexPath.section,indexPath.row];
  9. }
  10. cell.imageView.image = [UIImage imageNamed:@"a.png"];
  11. cell.detailTextLabel.text = @"這是詳細信息";
  12. return cell;
  13. }

2.4 完整代碼

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

 
  1. #import "TRAppDelegate.h"
  2. #import "TRMyTableViewController.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. TRMyTableViewController *myTVC = [[TRMyTableViewController alloc]initWithNibName:@"TRMyTableViewController" bundle:nil];
  10. self.window.rootViewController = myTVC;
  11. [self.window makeKeyAndVisible];
  12. return YES;
  13. }
  14. @end
 

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

 
  1. #import "TRMyTableViewController.h"
  2. @implementation TRMyTableViewController
  3. #pragma mark - Table view data source
  4. //如果不實現此方法,默認為1個分區
  5. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  6. {
  7. return 3;
  8. }
  9. -(NSInteger)tableView:(UITableView *)tableView
  10. numberOfRowsInSection:(NSInteger)section
  11. {
  12. if(section == 0) return 2;
  13. else if(section == 1) return 3;
  14. else if(section == 2) return 1500;
  15. return 0;
  16. }
  17. -(UITableViewCell *)tableView:(UITableView *)tableView
  18. cellForRowAtIndexPath:(NSIndexPath *)indexPath
  19. {
  20. UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
  21. if(indexPath.section == 0){
  22. cell.textLabel.text = [NSString stringWithFormat:@"第0區的第%i行",indexPath.row];
  23. }else{
  24. cell.textLabel.text = [NSString stringWithFormat:@"%i區%i行",indexPath.section,indexPath.row];
  25. }
  26. cell.imageView.image = [UIImage imageNamed:@"a.png"];
  27. cell.detailTextLabel.text = @"這是詳細信息";
  28. return cell;
  29. }
  30. @end
 

3 展示Cell重用時的數據處理

3.1 問題

表視圖在展現數據的時候,超出界面的單元格cell對象並不會被釋放,而是放入了tableView的用於管理單元格的隊列中,所以需要在創建cell對象之前先試着從此隊列中去拿已經存在的cell對象,如果能拿到就不需要再創建cell對象,而是重用此Cell對象,以減少對內存的占用,本案例將演示cell的重用過程。

3.2 方案

UITableViewCell的重用機制:

1)當tableView在創建每一個cell的時候會對cell做一個重用標記,該標記就是初始化方法initWithStyle:reuseIdentifier:的reuseIdentifier參數,是一個NSString類型;

2)當表視圖的單元格超出界面之后會將該單元格加入的tableView的單元格隊列中,因此每次創建cell之前都會做一個判斷,判斷tableView的單元格隊列中是否存在cell對象,如果有就直接使用,如果沒有就創建一個新的cell對象。

3.3 步驟

實現此案例需要按照如下步驟進行。

步驟一:定義一個重用標記

在tableView:cellForRowAtIndexPath:方法里面首先創建一個NSString類型的對象cellIdentifier用做重用標記,該對象是一個static類型,保證在程序結束之前不會被銷毀,代碼如下所示:

 
  1. static NSString *cellIdentifier = @"MyCell";

步驟二:判斷tableView的單元格隊列中是否存在cell對象

通過tabelView的dequeueReusableCellWithIdentifier:方法獲取 cell對象,如果該方法返回的cell對象不為空,說明有可重用的cell,identifier參數就是上一步所創建的重用標記cellIdentifier,代碼如下所示:

 
  1. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

步驟三:如果沒有可重用的cell則創建一個新的cell對象

通過上一步獲取到的cell對象如果為空,說明沒有可以重用的cell對象,則需要創建一個新的cell對象以供使用,代碼如下所示:

  1. if(cell==nil){
  2. cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
  3. }

3.4 完整代碼

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

 
  1. #import "TRTableViewController.h"
  2. @implementation TRTableViewController
  3. -(UITableViewCell *)tableView:(UITableView *)tableView
  4. cellForRowAtIndexPath:(NSIndexPath *)indexPath
  5. {
  6. static NSString *cellIdentifier = @"MyCell";
  7. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  8. if(cell==nil){
  9. cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
  10. }
  11. return cell;
  12. }
  13. @end
 

4 注冊Cell並重用

4.1 問題

本案例學習使用注冊cell的方式實現cell的重用。

4.2 方案

首先向tableView注冊一個重用的Cell類;

然后向tableView索要隊列中的Cell對象時,如果隊列中沒有Cell對象,tableView會自動創建一個並返回,這樣可以確保dequeue方法一定會返回一個Cell對象供使用。

4.3 步驟

實現此案例需要按照如下步驟進行。

步驟一:注冊cell

在TRTableViewController里面首先創建一個NSString類型的對象cellIdentifier用做重用標記,該對象是一個static類型,保證在程序結束之前不會被銷毀,代碼如下所示:

  1. static NSString *cellIdentifier = @"MyCell";

在viewDidLoad方法里面使用registerClass: forCellReuseIdentifier:方法注冊cell,代碼如下所示:

 
  1. - (void)viewDidLoad
  2. {
  3. [super viewDidLoad];
  4. //注冊一個Cell類型到tableView
  5. [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];
  6. }

步驟二:創建cell對象

在tableView: cellForRowAtIndexPath:方法里面創建cell對象,使用dequeueReusableCellWithIdentifier: forIndexPath:方法創建cell對象時,如果沒有可重用的cell會自動創建一個,因此能保證返回一個cell對象,代碼如下所示:

 
  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  2. {
  3. //只要注冊過Cell類型,此處tableView保證能返回一個Cell對象
  4. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
  5. return cell;
  6. }

4.4 完整代碼

 
  1. #import "TRTableViewController.h"
  2. @implementation TRTableViewController
  3. //定義cell的重用標識
  4. static NSString *cellIdentifier = @"MyCell";
  5. - (void)viewDidLoad
  6. {
  7. [super viewDidLoad];
  8. //注冊一個Cell類型到tableView
  9. [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];
  10. }
  11. //cellForRow方法里面的代碼
  12. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  13. {
  14. //只要注冊過Cell類型,此處tableView保證能返回一個Cell對象
  15. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
  16. cell.textLabel.text = self.data[indexPath.row];
  17. return cell;
  18. }
  19. @end
 

5 使用TableView展示數據列表

5.1 問題

為了使tableView顯示的數據更靈活,通常都會有一個NSArray類型的屬性來管理表視圖的數據,本案例在第三個案例(或者案例四)的基礎上讓表視圖展示一組字符串數據(城市名稱)。

5.2 方案

首先定義一個NSArray類型的屬性用於存儲表視圖的數據;

其次在TRAppDelegate的程序入口方法里面初始化數組;

最后在協議方法里面給表視圖加載數據。

5.3 步驟

實現此案例需要按照如下步驟進行。

步驟一:定義一個存儲數據的NSArray類型的屬性

為了使tableView顯示的數據更靈活,通常都會有一個NSArray類型的屬性來管理表視圖的數據,在TRTableViewController類里面定義一個公開的屬性NSArray類型的屬性data,代碼如下所示:

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

步驟二:初始化存儲數據的數組

在TRAppdelegate的程序入口方法里面對該屬性進行初始化,這里給一個模擬數據,代碼如下所示:

 
  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. TRTableViewController *tvc = [[TRTableViewController alloc]initWithNibName:@"TRTableViewController" bundle:nil];
  7. tvc.data = @[@"北京", @"上海", @"廣州", @"深圳", @"濟南",@"石家庄",@"武漢",@"鄭州",@"成都",@"重慶",@"珠海",@"香港",@"澳門"];
  8. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:tvc];
  9. self.window.rootViewController = navi;
  10. [self.window makeKeyAndVisible];
  11. return YES;
  12. }

步驟三:給表視圖加載數據

首先在tableView:numberOfRowsInSection:方法里面返回表視圖的行數,通常都是返回一個數組的count,本案例即self.data.count,代碼如下所示:

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

然后在TRTableViewController類里面的tableView:cellForRowAtIndexPath:的方法里面給表視圖加載數據,代碼如下所示:

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

運行程序實現效果如圖-6所示:

圖-6

步驟四:點擊某一行單元格

在點擊表視圖某一行時會調用tableView:didSelectRowAtIndexPath:方法,該方法是UITabelViewDelegate協議里面的方法,因此只需在TRTableViewController.m文件中實現該方法即可,indexPath參數就是被點擊的單元格的路徑,代碼如下所示:

  1. //當用戶點擊了某一行Cell時被調用
  2. -(void)tableView:(UITableView *)tableView
  3. didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  4. {
  5. NSLog(@"用戶點擊了%d區的%d行, %@", indexPath.section, indexPath.row, self.data[indexPath.row]);
  6. }

運行程序,點擊某一行可見控制台會輸出被點擊的地區名稱。

5.4 完整代碼

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

 
  1. #import "TRAppDelegate.h"
  2. #import "TRTableViewController.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. TRTableViewController *tvc = [[TRTableViewController alloc]initWithNibName:@"TRTableViewController" bundle:nil];
  10. tvc.data = @[@"北京", @"上海", @"廣州", @"深圳", @"濟南",@"石家庄",@"武漢",@"鄭州",@"成都",@"重慶",@"珠海",@"香港",@"澳門"];
  11. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:tvc];
  12. self.window.rootViewController = navi;
  13. [self.window makeKeyAndVisible];
  14. return YES;
  15. }
  16. @end
 

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

 
  1. #import "TRTableViewController.h"
  2. @implementation TRTableViewController
  3. - (void)viewDidLoad
  4. {
  5. [super viewDidLoad];
  6. self.title = @"地區";
  7. }
  8. -(NSInteger)tableView:(UITableView *)tableView
  9. numberOfRowsInSection:(NSInteger)section
  10. {
  11. return self.data.count;
  12. }
  13. -(UITableViewCell *)tableView:(UITableView *)tableView
  14. cellForRowAtIndexPath:(NSIndexPath *)indexPath
  15. {
  16. static NSString *cellIdentifier = @"MyCell";
  17. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  18. if(cell==nil){
  19. cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
  20. }
  21. cell.textLabel.text = self.data[indexPath.row];
  22. return cell;
  23. }
  24. @end
 

6 項目友錄中的朋友列表

6.1 問題

模擬系統的通訊錄功能,使用表視圖控制器展示聯系人界面,並實現添加聯系人功能,本案例表視圖需要展示的是一組對象數據,實現效果如圖-7、圖-8所示:

圖-7

圖-8

6.2 方案

首先創建一個SingleViewApplication項目,再創建一個表視圖控制器類TRContactTableViewController,該類有一個管理聯系人的NSMutableArray類型的屬性contacts。

在TRAppDelegate的程序入口方法里面創建一個帶有導航的表視圖控制器做為根視圖控制器。

其次根據本案例的需求創建一個聯系人類TRCantact類,用於保存聯系人信息。

然后創建一個TRInputViewController類繼承至UIViewController,用於管理編輯聯系人界面。再給TRContactTableViewController的導航欄添加一個編輯按鈕,點擊按鈕跳轉到編輯界面,並實現表視圖數據源協議方法。

最后在TRInputViewController類里面根據輸入的信息創建TRContact對象,然后通過委托的方式將新建聯系人對象傳遞給TRContactTableViewController類,並回退到聯系人界面。TRContactTableViewController類里面通過實現協議方法給聯系人頁面加載和更新數據。

6.3 步驟

實現此案例需要按照如下步驟進行。

步驟一:創建項目,設置根視圖控制器

創建一個SingleViewApplication項目,然后再創建一個表視圖控制器類TRContactTableViewController,並且定義一個用來管理聯系人的NSMutableArray類型的屬性contacts,代碼如下所示:

 
  1. @interface TRContactTableViewController ()
  2. @property(nonatomic, strong) NSMutableArray *contacts;
  3. @end
  4. //重寫setter方法,初始化實例變量_contacts
  5. - (NSMutableArray *)contacts
  6. {
  7. if(!_contacts){
  8. _contacts = [@[] mutableCopy];
  9. }
  10. return _contacts;
  11. }

在TRAppDelegate的程序入口方法里面創建一個帶有導航的表視圖控制器做為根視圖控制器,代碼如下所示:

 
  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. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:contactTVC];
  8. self.window.rootViewController = navi;
  9. [self.window makeKeyAndVisible];
  10. return YES;
  11. }

步驟二:創建TRContact聯系人類

創建一個TRContact類繼承至NSObject,並且定義兩個NSString類型的屬性name和phoneNumber,分別用於存儲聯系人的姓名和手機號,代碼如下所示:

 
  1. @property (nonatomic,copy)NSString *name;
  2. @property (nonatomic,copy)NSString *phoneNumber;

然后自定義一個初始化方法initWithName:andPhoneNumber:,方便外部創建聯系人對象的時候進行初始化,代碼如下所示:

 
  1. -(instancetype)initWithName:(NSString*)name
  2. andPhoneNumber:(NSString*)phoneNumber
  3. {
  4. self = [super init];
  5. if (self) {
  6. self.name = name;
  7. self.phoneNumber = phoneNumber;
  8. }
  9. return self;
  10. }

步驟三:創建TRInputViewController類,並實現頁面跳轉

創建一個TRInputViewController類,用於管理編輯聯系人界面,在xib文件中拖放兩個輸入框(接受用戶輸入的聯系人姓名和手機號),兩個label和一個按鈕,並在檢查器中設置相關屬性,這里需要注意將用於接收用戶輸入手機號的輸入框,鍵盤類型選擇NumberPad類型,完成效果如圖-9所示:

圖-9

然后給TRContactTableViewController的導航欄添加標題和編輯按鈕,點擊按鈕實現頁面的跳轉,這里使用present的方式跳轉頁面,新頁面會帶有一個新的導航控制器,代碼如下所示:

 
  1. - (void)viewDidLoad
  2. {
  3. [super viewDidLoad];
  4. //設置導航欄標題
  5. self.title = @"通訊錄";
  6. //給導航欄添加編輯按鈕,點擊按鈕會調用addContact:方法
  7. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addContact:)];
  8. }
  9. //實現addContact方法
  10. - (void)addContact:(UIBarButtonItem *)sender
  11. {
  12. TRInputViewController *inputVC = [[TRInputViewController alloc]initWithNibName:@"TRInputViewController" bundle:nil];
  13. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:inputVC];
  14. [self presentViewController:navi animated:YES completion:nil];
  15. }

實現表視圖數據源協議方法,完成數據加載代碼,這里只有一個分區,因此可不用實現分區方法默認返回1,行數直接返回self.contacts.count,在tableView: cellForRowAtIndexPath:方法里,讓cell的textLabel顯示聯系人的姓名,cell的detailTextLabel顯示聯系人的手機號,代碼如下所示:

 
  1. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  2. {
  3. return self.contacts.count;
  4. }
  5. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  6. {
  7. static NSString *CellIdentifier = @"Cell";
  8. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  9. if (cell == nil) {
  10. //創建cell時,類型選擇UITableViewCellStyleValue1,右邊顯示detailTextLabel
  11. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
  12. }
  13. //通過indexPath.row在self.contacts數組里面找到當前cell對應的聯系人對象
  14. TRContact *contact = self.contacts[indexPath.row];
  15. //cell.textLabel顯示聯系人姓名
  16. cell.textLabel.text = contact.name;
  17. //cell.detailTextLabel顯示聯系人的手機號
  18. cell.detailTextLabel.text = contact.phoneNumber;
  19. return cell;
  20. }

運行程序,界面效果如圖-10所示:

圖-10

從圖中可見目前聯系人頁面沒有任何信息,那是因為聯系人數組里面還沒有任何數據,下一步則是通過編輯頁面給聯系人數組添加數據。

步驟四:根據用戶的輸入創建聯系人對象並更新聯系人界面

將TRInputViewController界面上的兩個輸入框關聯成私有屬性nametextField和phoneNumberTextField,代碼如下所示:

  1. @property (weak, nonatomic) IBOutlet UITextField *nameTextField;
  2. @property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;

將確定按鈕關聯成私有方法submit,該方法的功能主要是根據用戶輸入的信息創建一個新的TRContact對象contact,並通過委托將contact對象傳遞給聯系人界面,最后返回聯系人界面。

因此首先需要在TRInputViewController.h文件里面定義一個協議TRInputViewDelegate和一個委托屬性,代碼如下所示:

 
  1. @class TRInputViewController;
  2. @protocol TRInputViewDelegate <NSObject>
  3. - (void)inputViewController:(TRInputViewController *)inputVC contact:(TRContact *)contact;
  4. @end
  5. @interface TRInputViewController : UIViewController
  6. //在創建TRInputViewController對象時對delegate屬性進行賦值確定被委托者
  7. @property (nonatomic, weak) id<TRInputViewDelegate> delegate;
  8. @end

然后實現submit方法,代碼如下所示:

  1. - (IBAction)submit
  2. {
  3. [self.phoneNumberTextField resignFirstResponder];
  4. //創建TRContact聯系人對象
  5. TRContact *contact = [[TRContact alloc]initWithName:self.nameTextField.text andPhoneNumber:self.phoneNumberTextField.text];
  6. //將contact對象傳遞給聯系人界面
  7. [self.delegate inputViewController:self contact:contact];
  8. [self dismissViewControllerAnimated:YES completion:nil];
  9. }

最后TRContactTableViewController遵守TRInputViewDelegate協議,並實現協議方法inputViewController:contact:,該方法里主要是根據傳遞過來的聯系人信息更新contacts數組和界面,這里使用reloadData方法刷新界面,代碼如下所示:

 
  1. //遵守協議
  2. @interface TRContactTableViewController () <TRInputViewDelegate>
  3. - (void)addContact:(UIBarButtonItem *)sender
  4. {
  5. TRInputViewController *inputVC = [[TRInputViewController alloc]initWithNibName:@"TRInputViewController" bundle:nil];
  6. //添加聯系人方法里面給inputVC.delegate賦值,指定當前對象為被委托者
  7. //添加聯系人方法里面給inputVC.delegate賦值,指定當前對象為被委托者
  8. inputVC.delegate = self;
  9. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:inputVC];
  10. [self presentViewController:navi animated:YES completion:nil];
  11. }
  12. //實現TRInputViewDelegate協議方法
  13. - (void)inputViewController:(TRInputViewController *)inputVC contact:(TRContact *)contact
  14. {
  15. //將傳遞過來的contact對象添加到聯系人數組
  16. [self.contacts addObject:contact];
  17. //重新加載數據,更新界面
  18. [self.tableView reloadData];
  19. }

6.4 完整代碼

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

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

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

 
  1. #import "TRContactTableViewController.h"
  2. #import "TRInputViewController.h"
  3. @interface TRContactTableViewController () <TRInputViewDelegate>
  4. @property(nonatomic, strong) NSMutableArray *contacts;
  5. @end
  6. @implementation TRContactTableViewController
  7. - (NSMutableArray *)contacts
  8. {
  9. if(!_contacts){
  10. _contacts = [@[] mutableCopy];
  11. }
  12. return _contacts;
  13. }
  14. //實現TRInputViewDelegate協議方法
  15. - (void)inputViewController:(TRInputViewController *)inputVC contact:(TRContact *)contact
  16. {
  17. [self.contacts addObject:contact];
  18. //重新加載數據
  19. [self.tableView reloadData];
  20. }
  21. - (void)viewDidLoad
  22. {
  23. [super viewDidLoad];
  24. self.title = @"通訊錄";
  25. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addContact:)];
  26. }
  27. - (void)addContact:(UIBarButtonItem *)sender
  28. {
  29. TRInputViewController *inputVC = [[TRInputViewController alloc]initWithNibName:@"TRInputViewController" bundle:nil];
  30. inputVC.delegate = self;
  31. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:inputVC];
  32. [self presentViewController:navi animated:YES completion:nil];
  33. }
  34. -(NSInteger)tableView:(UITableView *)tableView
  35. numberOfRowsInSection:(NSInteger)section
  36. {
  37. return self.contacts.count;
  38. }
  39. -(UITableViewCell *)tableView:(UITableView *)tableView
  40. cellForRowAtIndexPath:(NSIndexPath *)indexPath
  41. {
  42. static NSString *CellIdentifier = @"Cell";
  43. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  44. if (cell == nil) {
  45. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
  46. }
  47. TRContact *contact = self.contacts[indexPath.row];
  48. cell.textLabel.text = contact.name;
  49. cell.detailTextLabel.text = contact.phoneNumber;
  50. return cell;
  51. }
  52. @end
 

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

 
  1. #import <UIKit/UIKit.h>
  2. #import "TRContact.h"
  3. @class TRInputViewController;
  4. @protocol TRInputViewDelegate <NSObject>
  5. -(void)inputViewController:(TRInputViewController *)inputVC
  6. contact:(TRContact *)contact;
  7. @end
  8. @interface TRInputViewController : UIViewController
  9. @property (nonatomic, weak) id<TRInputViewDelegate> delegate;
  10. @end
 

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

 
  1. #import "TRInputViewController.h"
  2. @interface TRInputViewController ()
  3. @property (weak, nonatomic) IBOutlet UITextField *nameTextField;
  4. @property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
  5. @end
  6. @implementation TRInputViewController
  7. - (IBAction)submit
  8. {
  9. [self.phoneNumberTextField resignFirstResponder];
  10. TRContact *contact = [[TRContact alloc]initWithName:self.nameTextField.text andPhoneNumber:self.phoneNumberTextField.text];
  11. [self.delegate inputViewController:self contact:contact];
  12. [self dismissViewControllerAnimated:YES completion:nil];
  13. }
  14. - (IBAction)next {
  15. [self.nameTextField resignFirstResponder];
  16. [self.phoneNumberTextField becomeFirstResponder];
  17. }
  18. @end
 

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

 
  1. #import <Foundation/Foundation.h>
  2. @interface TRContact : NSObject
  3. @property (nonatomic,copy)NSString *name;
  4. @property (nonatomic,copy)NSString *phoneNumber;
  5. -(instancetype)initWithName:(NSString*)name
  6. andPhoneNumber:(NSString*)phoneNumber;
  7. @end
 

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

 
  1. #import "TRContact.h"
  2. @implementation TRContact
  3. -(instancetype)initWithName:(NSString*)name
  4. andPhoneNumber:(NSString*)phoneNumber
  5. {
  6. self = [super init];
  7. if (self) {
  8. self.name = name;
  9. self.phoneNumber = phoneNumber;
  10. }
  11. return self;
  12. }
  13. @end
 

7 增加一個新朋友

7.1 問題

上一個案例已經實現的通訊錄的展示聯系人、添加聯系人功能,刷新界面的時候使用reloadData方法,本案例將使用另外一種局部更新界面的方式更新聯系人界面。

7.2 方案

本案例直接在上一個案例上做修改,主要是重寫TRContactTableViewController類里面更新界面的代碼,reloadData方法更新整個界面,也就是會將整個表視圖的數據重新加載一遍,本案例采用insertRowsAtIndexPath方法局部更新界面。

7.3 步驟

實現此案例需要按照如下步驟進行。

步驟一:使用insertRowsAtIndexPath方法局部更新界面

insertRowsAtIndexPath方法主要用於在表視圖里面插入一行單元格,indexPath參數是該單元格插入的位置,是一個NSIndexPath類型的參數,因此在inputViewController:contact:方法里面,首先同樣的將傳遞過來的contact添加到數組,然后找到插入單元格的位置,使用insertRowsAtIndexPath方法在表視圖里面插入單元格,代碼如下所示:

 
  1. - (void)inputViewController:(TRInputViewController *)inputVC contact:(TRContact *)contact
  2. {
  3. [self.contacts addObject:contact];
  4. //創建一個NSIndexPath對象,插入單元格的位置
  5. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.contacts.count - 1 inSection:0];
  6. //表視圖中插入單元格
  7. [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
  8. }

7.4 完整代碼

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

 
  1. #import "TRContactTableViewController.h"
  2. #import "TRInputViewController.h"
  3. @interface TRContactTableViewController () <TRInputViewDelegate>
  4. @property(nonatomic, strong) NSMutableArray *contacts;
  5. @end
  6. @implementation TRContactTableViewController
  7. - (NSMutableArray *)contacts
  8. {
  9. if(!_contacts){
  10. _contacts = [@[] mutableCopy];
  11. }
  12. return _contacts;
  13. }
  14. //實現TRInputViewDelegate協議方法
  15. -(void)inputViewController:(TRInputViewController *)inputVC
  16. contact:(TRContact *)contact
  17. {
  18. [self.contacts addObject:contact];
  19. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.contacts.count - 1 inSection:0];
  20. [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
  21. }
  22. - (void)viewDidLoad
  23. {
  24. [super viewDidLoad];
  25. self.title = @"通訊錄";
  26. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addContact:)];
  27. }
  28. - (void)addContact:(UIBarButtonItem *)sender
  29. {
  30. TRInputViewController *inputVC = [[TRInputViewController alloc]initWithNibName:@"TRInputViewController" bundle:nil];
  31. inputVC.delegate = self;
  32. UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:inputVC];
  33. [self presentViewController:navi animated:YES completion:nil];
  34. }
  35. -(NSInteger)tableView:(UITableView *)tableView
  36. numberOfRowsInSection:(NSInteger)section
  37. {
  38. return self.contacts.count;
  39. }
  40. -(UITableViewCell *)tableView:(UITableView *)tableView
  41. cellForRowAtIndexPath:(NSIndexPath *)indexPath
  42. {
  43. static NSString *CellIdentifier = @"Cell";
  44. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  45. if (cell == nil) {
  46. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
  47. }
  48. TRContact *contact = self.contacts[indexPath.row];
  49. cell.textLabel.text = contact.name;
  50. cell.detailTextLabel.text = contact.phoneNumber;
  51. return cell;
  52. }
  53. @end


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM