一、基本介紹
在眾多移動應?用中,能看到各式各樣的表格數據 。
在iOS中,要實現表格數據展示,最常用的做法就是使用UITableView,UITableView繼承自UIScrollView,因此支持垂直滾動,?且性能極佳 。
UITableview有分組和不分組兩種樣式,可以在storyboard或者是用代碼設置。
二、數據展示
UITableView需要?一個數據源(dataSource)來顯示數據 UITableView會向數據源查詢一共有多少行數據以及每?行顯示什么數據等
沒有設置數據源的UITableView只是個空殼
凡是遵守UITableViewDataSource協議的OC對象,都可以是UITableView的數據源?
?
展示數據的過程:
(1)調用數據源的下面?法得知?一共有多少組數據 - (NSInteger)numberOfSectionsInTableView:(UITableView?*)tableView;
(2)調用數據源的下面?法得知每一組有多少行數據 - (NSInteger)tableView:(UITableView *)tableView?numberOfRowsInSection:(NSInteger)section;
(3)調?數據源的下??法得知每??顯示什么內容
- (UITableViewCell *)tableView:(UITableView *)tableView?cellForRowAtIndexPath:(NSIndexPath *)indexPath;
三、代碼示例
更多相關APP開發資訊關注:appyykf
?
(1)能基本展示的“垃圾”代碼
1 #import "NJViewController.h"
2 3 @interface NJViewController ()<UITableViewDataSource> 4 @property (weak, nonatomic) IBOutlet UITableView *tableView; 5 6 @end 7 8 @implementation NJViewController 9 10 - (void)viewDidLoad 11 { 12 [super viewDidLoad]; 13 // 設置tableView的數據源 14 self.tableView.dataSource = self; 15 16 } 17 18 #pragma mark - UITableViewDataSource 19 /** 20 * 1.告訴tableview一共有多少組 21 */ 22 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 23 { 24 NSLog(@"numberOfSectionsInTableView"); 25 return 2; 26 } 27 /** 28 * 2.第section組有多少行 29 */ 30 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 31 { 32 NSLog(@"numberOfRowsInSection %d", section); 33 if (0 == section) { 34 // 第0組有多少行 35 return 2; 36 }else 37 { 38 // 第1組有多少行 39 return 3; 40 } 41 } 42 /** 43 * 3.告知系統每一行顯示什么內容 44 */ 45 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 46 { 47 NSLog(@"cellForRowAtIndexPath %d %d", indexPath.section, indexPath.row); 48 // indexPath.section; // 第幾組 49 // indexPath.row; // 第幾行 50 // 1.創建cell 51 UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil]; 52 53 // 2.設置數據 54 // cell.textLabel.text = @"汽車"; 55 // 判斷是第幾組的第幾行 56 if (0 == indexPath.section) { // 第0組 57 if (0 == indexPath.row) // 第0組第0行 58 { 59 cell.textLabel.text = @"奧迪"; 60 }else if (1 == indexPath.row) // 第0組第1行 61 { 62 cell.textLabel.text = @"寶馬"; 63 } 64 65 }else if (1 == indexPath.section) // 第1組 66 { 67 if (0 == indexPath.row) { // 第0組第0行 68 cell.textLabel.text = @"本田"; 69 }else if (1 == indexPath.row) // 第0組第1行 70 { 71 cell.textLabel.text = @"豐田"; 72 }else if (2 == indexPath.row) // 第0組第2行 73 { 74 cell.textLabel.text = @"馬自達"; 75 } 76 } 77 78 // 3.返回要顯示的控件 79 return cell; 80 81 } 82 /** 83