IOS UITableView详细使用

本文详细介绍了UITableView的使用方法,包括初始化、配置、创建单元格、管理选择及编辑等关键功能。同时,提供了完整的代码示例来展示如何实现一个多节、可编辑的表格视图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

.h文件

  1. #import <UIKit/UIKit.h>  
  2.   
  3. @interface EXTVV2ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>  
  4.   
  5. @end  


.m文件

  1. //  
  2. //  EXTVV2ViewController.m  
  3. //  ExerciseTableViewV2  
  4. //  
  5. //  Created by hxl on 13-5-20.  
  6. //  Copyright (c) 2013年 xiaolei.hu. All rights reserved.  
  7. //  
  8.   
  9. /* 
  10.  UITableView 
  11.  Tasks 
  12.   
  13.  //初始化UITableView对象 
  14.  Initializing a UITableView Object 
  15.   
  16.  – initWithFrame:style: 
  17.  - (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style 
  18.   
  19.   
  20.  //配置UITableView 
  21.  Configuring a Table View 
  22.   
  23.  //tableView的style 
  24.  //UITableViewStylePlain或者UITableViewStyleGrouped,2者选1 
  25.  style  property 
  26.  @property(nonatomic, readonly) UITableViewStyle style 
  27.   
  28.  //当前section有多少行(此方法必须实现) 
  29.  – numberOfRowsInSection: 
  30.  - (NSInteger)numberOfRowsInSection:(NSInteger)section 
  31.  //当前section的标示 
  32.   
  33.   
  34.  //当前tableView里有多少section,默认为1 
  35.  – numberOfSections 
  36.  - (NSInteger)numberOfSections 
  37.   
  38.   
  39.  //行高 
  40.  rowHeight  property 
  41.   
  42.   
  43.  separatorStyle  property 
  44.  separatorColor  property 
  45.  //tableview的背景 
  46.  backgroundView  property 
  47.   
  48.   
  49.   
  50.  //创建cell 
  51.  Creating Table View Cells 
  52.  – registerNib:forCellReuseIdentifier: 
  53.  – registerClass:forCellReuseIdentifier: 
  54.  – dequeueReusableCellWithIdentifier:forIndexPath: 
  55.  – dequeueReusableCellWithIdentifier: 
  56.   
  57.   
  58.   
  59.   
  60.  Accessing Header and Footer Views 
  61.  – registerNib:forHeaderFooterViewReuseIdentifier: 
  62.  – registerClass:forHeaderFooterViewReuseIdentifier: 
  63.  – dequeueReusableHeaderFooterViewWithIdentifier: 
  64.  tableHeaderView  property 
  65.  tableFooterView  property 
  66.  sectionHeaderHeight  property 
  67.  sectionFooterHeight  property 
  68.  – headerViewForSection: 
  69.  – footerViewForSection: 
  70.  Accessing Cells and Sections 
  71.  – cellForRowAtIndexPath: 
  72.  – indexPathForCell: 
  73.  – indexPathForRowAtPoint: 
  74.  – indexPathsForRowsInRect: 
  75.  – visibleCells 
  76.  – indexPathsForVisibleRows 
  77.  Scrolling the Table View 
  78.  – scrollToRowAtIndexPath:atScrollPosition:animated: 
  79.  – scrollToNearestSelectedRowAtScrollPosition:animated: 
  80.  Managing Selections 
  81.  – indexPathForSelectedRow 
  82.  – indexPathsForSelectedRows 
  83.  – selectRowAtIndexPath:animated:scrollPosition: 
  84.  – deselectRowAtIndexPath:animated: 
  85.  allowsSelection  property 
  86.  allowsMultipleSelection  property 
  87.  allowsSelectionDuringEditing  property 
  88.  allowsMultipleSelectionDuringEditing  property 
  89.  Inserting, Deleting, and Moving Rows and Sections 
  90.  – beginUpdates 
  91.  – endUpdates 
  92.  – insertRowsAtIndexPaths:withRowAnimation: 
  93.  – deleteRowsAtIndexPaths:withRowAnimation: 
  94.  – moveRowAtIndexPath:toIndexPath: 
  95.  – insertSections:withRowAnimation: 
  96.  – deleteSections:withRowAnimation: 
  97.  – moveSection:toSection: 
  98.  Managing the Editing of Table Cells 
  99.  editing  property 
  100.  – setEditing:animated: 
  101.  Reloading the Table View 
  102.  – reloadData 
  103.  – reloadRowsAtIndexPaths:withRowAnimation: 
  104.  – reloadSections:withRowAnimation: 
  105.  – reloadSectionIndexTitles 
  106.  Accessing Drawing Areas of the Table View 
  107.  – rectForSection: 
  108.  – rectForRowAtIndexPath: 
  109.  – rectForFooterInSection: 
  110.  – rectForHeaderInSection: 
  111.  Managing the Delegate and the Data Source 
  112.  dataSource  property 
  113.  delegate  property 
  114.  Configuring the Table Index 
  115.  sectionIndexMinimumDisplayRowCount  property 
  116.  sectionIndexColor  property 
  117.  sectionIndexTrackingBackgroundColor  property 
  118.   
  119.  */  
  120.   
  121. #import "EXTVV2ViewController.h"  
  122.   
  123. @interface EXTVV2ViewController ()  
  124. @property (nonatomic) NSMutableArray *listData;  
  125. @property (nonatomic) IBOutlet UITableView* myTableView;//在xib中与tableview控件关联  
  126. @property (nonatomic) IBOutlet UISwitch* mySwitch;//在xib中与switch控件关联  
  127. -(IBAction)switchEditModel:(UISwitch*)sender;//在xib中与switch控件的事件关联  
  128. @end  
  129.   
  130. @implementation EXTVV2ViewController  
  131. @synthesize listData;  
  132. @synthesize myTableView;  
  133. @synthesize mySwitch;  
  134.   
  135. - (void)viewDidLoad  
  136. {  
  137.     [superviewDidLoad];  
  138.       
  139. // Do any additional setup after loading the view, typically from a nib.  
  140.     [selfsetListData:[selfcreateData:26sectionRowLength:10stringLength:6]];  
  141. }  
  142.   
  143. - (void)didReceiveMemoryWarning  
  144. {  
  145.     [superdidReceiveMemoryWarning];  
  146.     // Dispose of any resources that can be recreated.  
  147. }  
  148.   
  149. //指定有多少个分区(Section),默认为1  
  150. /* 
  151.  1.此处根据二维数组外层的count获取section数量 
  152.  此时已有count个section被创建 
  153.  */  
  154. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {  
  155.     return [self.listDatacount];  
  156. }  
  157.   
  158.   
  159. //指定各个分区中有多少行,默认为1。  
  160. /* 
  161.  2.此处根据1设置的section数量获取数组二维内层长度(row数量)ps:section会根据你设置的最大值自动递增 
  162.  此时section对应的count个cell被创建 
  163.  */  
  164. - (NSInteger) tableView: (UITableView *) tableView  
  165.   numberOfRowsInSection: (NSInteger) section {  
  166.     NSInteger rowCount = 0;  
  167.     //NSLog(@"section = %d",section);0/1/2  
  168.     if (section < self.listData.count) {  
  169.         rowCount = [self.listData[section]count];  
  170.     }  
  171.     return rowCount;  
  172. }  
  173.   
  174. //设置每行调用的cell  
  175. /* 
  176.  3.此处根据1设置的section数量,和2设置的row数量获取数组内容并填充cell 
  177.  对1、2创建的容器进行填充,section和row就是二维数组的下标 
  178.  */  
  179. - (UITableViewCell *) tableView: (UITableView *) tableView  
  180.           cellForRowAtIndexPath: (NSIndexPath *) indexPath  
  181. {  
  182.     /* 
  183.      indexPath 索引路径 
  184.      property: 
  185.      row:table view 中 
  186.      item:collection view中 
  187.      section:table/collection view中 
  188.      method 
  189.      //collection view中 
  190.      + (NSIndexPath *)indexPathForItem:(NSInteger)item inSection:(NSInteger)section 
  191.      //table view 中 
  192.      + (NSIndexPath *)indexPathForRow:(NSInteger)row inSection:(NSInteger)section 
  193.       
  194.      */  
  195.       
  196.     //产生一个静态标示(每个cell形式相同可用)  
  197.     //static NSString * TableSampleIdentifier = @ "TableSampleIdentifier";  
  198.     //每个cell形式不相同需要不同标示  
  199.     NSString * TableSampleIdentifier = [[NSStringalloc]initWithFormat:@"CMainCell%d", indexPath.row];  
  200.       
  201.     //通过标示符获取一个cell对象(dequeueReusableCellWithIdentifier=>系统请求的回调函数)  
  202.     UITableViewCell * cell = [tableViewdequeueReusableCellWithIdentifier:  
  203.                               TableSampleIdentifier];  
  204.     //如果未获取到cell对象,创建新的cell对象,并赋予标示符  
  205.     if (cell == nil) {  
  206.         cell = [[UITableViewCellalloc]  
  207.                 initWithStyle:UITableViewCellStyleDefault  
  208.                 reuseIdentifier: TableSampleIdentifier];  
  209.     }  
  210.     NSString* cellText = nil;  
  211.     if (indexPath.section <self.listData.count) {  
  212.         NSArray* rowArray = self.listData[indexPath.section];  
  213.         if ([indexPath row] < rowArray.count) {  
  214.             cellText = rowArray[indexPath.row];  
  215.         }  
  216.     }  
  217.     cell.textLabel.text = cellText;  
  218.     return cell;  
  219. }  
  220.   
  221. //设置每个section显示的Title  
  222. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section  
  223. {  
  224.     NSString* title = nil;  
  225.     if (section < self.listData.count) {  
  226.         NSArray* rowArray = self.listData[section];  
  227.         if (rowArray.count >0) {  
  228.             //将每个section的第一行作为title是惯例  
  229.             title = rowArray[0];  
  230.         }  
  231.     }  
  232.     //截取首字母  
  233.     return [titlesubstringToIndex:1];  
  234. }  
  235.   
  236. //设置tableview每行的title(右侧索引)  
  237. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{  
  238.     //initWithCapacity初始化数组时候指定长度  
  239.     NSMutableArray* indexTitleArray = [[NSMutableArrayalloc]initWithCapacity:[self.listDatacount]];  
  240.     //循环外围数组(section个数)  
  241.     for (UInt16 i =0; i < [self.listDatacount]; i++) {  
  242.         NSArray* rowArray = self.listData[i];  
  243.         //判断section下的数据行是否大于0  
  244.         if (rowArray.count >0) {  
  245.             NSString* titleStr = rowArray[0];  
  246.             //title长度超过3截取字符串  
  247.             if (titleStr.length >1) {  
  248.                 titleStr = [titleStr substringToIndex:1];  
  249.             }  
  250.             [indexTitleArray addObject:titleStr];  
  251.         }  
  252.     }  
  253.     //arrayWithArray产生一个新数组并释放原来的数组  
  254.     return [NSArrayarrayWithArray:indexTitleArray];  
  255. }  
  256.   
  257. //点击右侧索引时响应跳转到那个section的事件  
  258. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index  
  259. {  
  260.     return index;  
  261. }  
  262.   
  263.   
  264. //设置选中Cell的响应事件  
  265. /* 
  266.  -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
  267.  { 
  268.  [tableView deselectRowAtIndexPath:indexPath animated:YES];//选中后的反显颜色即刻消失 
  269.  } 
  270.  */  
  271.   
  272. //选中之前执行  
  273. -(NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath  
  274. {  
  275.     return indexPath;  
  276. }  
  277.   
  278. //设置划动cell是否出现del按钮  
  279. -(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath  
  280. {  
  281.     return YES;  
  282. }  
  283.   
  284. //设置删除时编辑状态  
  285. -(void)tableView:(UITableView *)tableView  commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath  
  286. {  
  287.     //删除元素的操作  
  288.     if (editingStyle ==UITableViewCellEditingStyleDelete)  
  289.     {  
  290.         //删除数据  
  291.         [self.listData[indexPath.section]removeObjectAtIndex:indexPath.row];  
  292.         //删除元素  
  293.         [tableView deleteRowsAtIndexPaths:[NSMutableArrayarrayWithObjects:indexPath,nil]withRowAnimation:UITableViewRowAnimationTop];  
  294.           
  295.     }  
  296. }  
  297.   
  298. //选中cell后触发的事件  
  299. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  
  300. {  
  301.       
  302.     //设置选中的样式,4种风格 UITableViewCellAccessoryCheckmark UITableViewCellAccessoryDetailDisclosureButton  
  303.     //UITableViewCellAccessoryDisclosureIndicator UITableViewCellAccessoryNone  
  304.     UITableViewCell *cellView = [tableView cellForRowAtIndexPath:indexPath];  
  305.     if (cellView.accessoryType ==UITableViewCellAccessoryNone) {  
  306.         cellView.accessoryType=UITableViewCellAccessoryCheckmark;  
  307.     }  
  308.     else {  
  309.         cellView.accessoryType =UITableViewCellAccessoryNone;  
  310.         [tableView deselectRowAtIndexPath:indexPathanimated:YES];  
  311.     }  
  312.       
  313.     //弹出框  
  314.     NSString *cellSelected=[self.listData[indexPath.section]objectAtIndex:indexPath.row];  
  315.     //indexPath.row得到选中的行号,提取出在数组中的内容。  
  316.     UIAlertView *myAlertView;  
  317.     myAlertView = [[UIAlertViewalloc]initWithTitle:@"你选中了:" message:cellSelected delegate:selfcancelButtonTitle:@"ok"otherButtonTitles:nil];  
  318.     //点击后弹出该对话框。  
  319.     [myAlertView show];  
  320.       
  321. }  
  322.   
  323. //是否能移动  
  324. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {  
  325.     return YES;  
  326. }  
  327.   
  328. //移动操作  
  329. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath  
  330. {  
  331.     if (sourceIndexPath != destinationIndexPath) {  
  332.         id object = [self.listData[sourceIndexPath.section]objectAtIndex:sourceIndexPath.row];  
  333.         [self.listData[sourceIndexPath.section]removeObjectAtIndex:sourceIndexPath.row];  
  334.         if (destinationIndexPath.row > [self.listData[destinationIndexPath.section]count]) {  
  335.             [self.listData[destinationIndexPath.section]addObject:object];  
  336.         }  
  337.         else {  
  338.             [self.listData[destinationIndexPath.section]insertObject:objectatIndex:destinationIndexPath.row];  
  339.         }  
  340.     }  
  341. }  
  342.   
  343. //单元格返回的编辑风格,包括删除 添加和默认  和不可编辑三种风格  
  344. //-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath  
  345. //{  
  346. //return UITableViewCellEditingStyleDelete;  
  347. //return UITableViewCellEditingStyleNone;  
  348. //return UITableViewCellEditingStyleInsert;  
  349. //}  
  350.   
  351. //switc按钮事件  
  352. -(IBAction)switchEditModel:(UISwitch*)sender  
  353. {  
  354.     //self.view.subview所有子视图,包括tableview等  
  355.     //是否开启编辑模式  
  356.     if(sender.on) {  
  357.         [self.myTableViewsetEditing:YESanimated:YES];  
  358.     } else {  
  359.         [self.myTableViewsetEditing:NOanimated:YES];  
  360.     }  
  361.       
  362. }  
  363.   
  364.   
  365. //生成随机字符串  
  366. - (NSString *) createRandString:(NSInteger)stringLength perStr:(UInt16)pstr{  
  367.     UInt16 seed = 0;  
  368.     //97-122小写英语  
  369.     NSMutableString *str = [[NSMutableStringalloc]initWithFormat:@"%c", pstr];  
  370.     for(UInt16 i = 0; i < stringLength; i++) {  
  371.         seed = (arc4random() % 26) + 97;  
  372.         [str appendFormat:@"%c", seed];  
  373.     }  
  374.     return [NSStringstringWithString:str];  
  375. }  
  376.   
  377. - (NSMutableArray *) createData:(NSInteger)sectionLength sectionRowLength:(NSInteger)row stringLength:(NSInteger)length{  
  378.     NSMutableArray *sectionData = [[NSMutableArrayalloc]initWithCapacity:sectionLength];  
  379.     for (UInt16 i =0; i < sectionLength ; i++) {  
  380.         NSMutableArray* rowData = [[NSMutableArrayalloc]initWithCapacity:row];  
  381.         for (UInt16 j =0; j < row; j++) {  
  382.             [rowData addObject:[selfcreateRandString:lengthperStr:i +97]];  
  383.         }  
  384.         [sectionData addObject:rowData];  
  385.     }  
  386.     return sectionData;  
  387. }  
  388. @end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值