一個簡單的TableView

任務

一個最簡單的TableView Demo,用以顯示姓名,點擊item,彈出一個姓名的提示。

相關概念

1、UITableView:繼承自UIScrollView,與之相關有兩個協(xié)議:UITableViewDelegate協(xié)議和UITableViewDataSource協(xié)議。?

它可以被分為多個,每個段包含單行或多行。?

而其中的每一行被稱為單元(UITableViewCell)。

2、協(xié)議:是類要實現(xiàn)的一系列方法等列表。

@protocol SomeProtocol[methoddeclarations]@end

1

2

3

3、數(shù)據(jù)源的兩個關鍵方法?

當表視圖需要顯示數(shù)據(jù)時,它需要先知道兩件事:有多少行需要顯示;每行要顯示什么內容。?

而這兩個問題可以用數(shù)據(jù)源的兩個方法來回答:

-(NSInteger)numberOfRowsInSection:(NSInteger)section-(UITableViewCell*)cellForRowAtIndexPath:(NSIndexPath*)indexPath

1

2

4、委托協(xié)議的一個關鍵方法?

當我們選中了一個單元,表視圖會和它的委托通信,告知某一單元被選中(被點擊),下面的方法會被調用。

-(void)tableView:(UITableView*)tableView? ? didSelectRowAtIndexPath:(NSIndexPath*)indexPath {? ? }

1

2

3

4

行動

1、新建一個項目,名稱為SimpleTableView。?

2、storyboard中加入一個表視圖?

在object library中搜索Table View并將其拖拽到主視圖中。在attributes inspector中將prototype cells改為1?

3、設置單元格的標識符?

這個標識符設置的目的是讓這個單元格(Cell)能夠被重用。見上圖,設為NameIdentifier。

4、可以編碼了?

1) ViewController.h 加入數(shù)據(jù)源和視圖委托協(xié)議

@interfaceViewController:UIViewController

1

2

2) ViewController.m 進行類的擴展,加入姓名數(shù)組

@interfaceViewController() {NSArray* data;}@end

1

2

3

4

5

6

3) 姓名數(shù)組初始化

- (void)viewDidLoad {? ? [super viewDidLoad];? ? //Doanyadditional setupafterloading theview, typicallyfroma nib.? ? data = @[@"張飛",@"趙云",@"劉備",@"關羽",@"馬操",@"孔明",? ? ? ? ? ? @"魏延",@"姜維",@"劉禪"];}

1

2

3

4

5

6

4) 實現(xiàn)兩個數(shù)據(jù)源的核心方法

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {returndata.count;}- (UITableViewCell*)tableView:(UITableView*)tableView? ? ? ? cellForRowAtIndexPath:(NSIndexPath*)indexPath {staticNSString*CellIdentifier = @"NameIdentifier";UITableViewCell*cell = [tableView? ? ? ? ? ? ? ? ? ? ? ? ? ? dequeueReusableCellWithIdentifier:CellIdentifier? ? ? ? ? ? ? ? ? ? ? ? ? ? forIndexPath:indexPath];NSString*name = data[indexPath.row];? ? cell.textLabel.text= name;returncell;}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

5) 實現(xiàn)視圖委托的核心方法?

選中一個item后,顯示一個提示信息

- (void)tableView:(UITableView*)tableViewdidSelectRowAtIndexPath:(NSIndexPath*)indexPath {// 聲明一個UIAlertViewUIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示"message:data[indexPath.row] delegate:selfcancelButtonTitle:nilotherButtonTitles:nil,nil];// 顯示 UIAlertView[alert show];// 添加延遲時間為 1.0 秒 然后執(zhí)行 dismiss: 方法[selfperformSelector:@selector(dismiss:) withObject:alert afterDelay:1.0];}- (void)dismiss:(UIAlertView *)alert{// 此處即相當于點擊了 cancel 按鈕[alert dismissWithClickedButtonIndex:[alert cancelButtonIndex] animated:YES];}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

5、最后一件最重要的事?

ViewControll中的數(shù)據(jù)源和視圖委托兩個協(xié)議要與表視圖相關聯(lián)起來,這里依然是一個拖拽操作(忍不住要吐槽)。?

在storyboard中,右擊Table View,然后將outlet中的datasource和dalegate拖拽到View Controll中。如下圖。?

運行到效果如下:?

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容