构造和使用UITableView

来源:互联网 发布:大河网络传媒有限公司 编辑:程序博客网 时间:2024/06/05 11:52


简而言之,Table View 是一个被分成不同部分的滚动视图,每部分又进一步被分成行。每行是一个 UITableViewCell 类的实例。


1、实例化Table View

有 2 个办法可以实例化 Table View:
     → 通过代码
     → 使用界面生成器
如果你使用界面生成器,创建一个 Table View 就是简单的把一个 Table View 从对象库拖

拽到你的.xib 文件中。如果你使用代码创建组建更顺手的话,也没有问题。你必须做的事情就是把 UITableView 类的一个对象实例化,让我们通过定义在视图控制器的头文件中定义我们的 Table View 开始:

#import <UIKit/UIKit.h>@interface Instantiating_a_Table_ViewViewController : UIViewController @property (nonatomic, strong) UITableView *myTableView;@end

然后我们会继续并在视图控制器的实现文件中合成我们的 Table View:

#import "Instantiating_a_Table_ViewViewController.h"  @implementation Instantiating_a_Table_ViewViewController  @synthesize myTableView; - (void)viewDidLoad {              [super viewDidLoad];              self.view.backgroundColor = [UIColor whiteColor];             self.myTableView =[[UITableView alloc] initWithFrame:self.view.boundsstyle:UITableViewStylePlain];           [self.view addSubview:self.myTableView]; }


视图控制器中初始值设定项 initWithFrame:style:的样式参数允许我们指定我们需要哪种类型的 Table View。有 2 种风格我们可以选择:

UITableViewStylePlain创建一个没有背景图片的空白 Table ViewUITableViewStyleGrouped

2、UITableViewDelegate、UITableViewDataSource

UITableViewDelegate中的方法全是@optional类型的,下面列出其中的几个方法及其用法:

 

- (CGFloat)tableView:(UITableView *)tableViewheightForRowAtIndexPath:(NSIndexPath *)indexPath//设置每个cell的高度 {            if (!indexPath.row)               {                        return 60;                }else                      {                             return 100;                       } }  - (CGFloat)tableView:(UITableView *)tableViewheightForHeaderInSection:(NSInteger)section//设置每个部分头部的高度 {       return 50.0f; }  -(CGFloat)tableView:(UITableView *)tableViewheightForFooterInSection:(NSInteger)section//设置每个部分底部的高度 {     if(section == 0)     {         return 80.0f;     }else    {         return 0;      } }  - (UIView *)tableView:(UITableView *)tableViewviewForHeaderInSection:(NSInteger)section//设置每个部分的头不是图 {            if (section== 0)              {                        UIView *firstSectionHeaderV = [selfinitSectionHeaderViewWithLeftLabel:@"选择搜索条件"andRightTitle:nil];                     [selfinitClearButtonInView:firstSectionHeaderV];                         return firstSectionHeaderV;              }else    {                                       NSArray *historys1 =[[NSArray alloc] initWithContentsOfFile:[self filePath]];                                 UIView *secondSectionHeaderV = [selfinitSectionHeaderViewWithLeftLabel:@"我的历史搜索"andRightTitle:[NSString stringWithFormat:@"%d条",[historys1 count]>5?5:[historys1count]]];                                  UIImageView *arrow =[[[UIImageView alloc] initWithImage:[UIImageimageNamed:@"arrowup.png"]] autorelease];                                arrow.frame = CGRectMake(290, 18, 10,10);                                  [secondSectionHeaderVaddSubview:arrow];                                    [historys1 release];                                  return secondSectionHeaderV;                        }    } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath//推到下一个界面{        switch (indexPath.row)        {            case 0:                                break;            case 1:                [self pushToParameter:indexPath.row];                break;            case 2:                [self pushToParameter:indexPath.row];                break;            case 3:                [self pushToParameter:indexPath.row];                break;            default:                break;        }}

UITableViewDataSource:

UITableView 类定义了一个调用 dataSource的属性,这个非类型化的对象必须遵循UITableViewDataSource协议,每次刷新表格视图,并重新加载使用 reloadData 方法时这个Table View会从其数据源调用各种方法以找出你打算对其填充的数据

numberOfSectionsInTableView: 此方法允许数据源告知必须加载到 Table View中的表的 Section数。tableView:numberOfRowsInSection:此方法告诉视图控制器有多少单元格或者行要下载到每个 Section,Section个数传递给

数据源中的 numberOfRowsInSection作参数,这个方法在数据源对象中要强制执行。tableView:cellForRowAtIndexPath:此方法负责返回作为 Table View行的 UITableViewCell类静态实例。这个方法在数据源

对象的执行中也是强制性的。所以我们来在视图控制器中执行逐个执行这些方法。首先,我们告诉 Table View我们要它呈现 3Section:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { NSInteger result = 0; if ([tableView isEqual:self.myTableView])  { result = 3; } return result; }

然后我们告诉表视图需要它在每个 Section呈现多少行:

- (NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger)section{  NSInteger result = 0; if ([tableView isEqual:self.myTableView]){  switch (section)  {case 0:  { result = 3; break;  }case 1:  {  result = 5;break;  }case 2:  {  result = 8;break;  }  }  } return result;}


 

现在,我们要求 Table View首先呈现 3 Section,第一个 Section3;第二个 Section5,第三个 Section8行。然后呢?返回 Table Viewcell的静态实例给 tableview,我们想要tablview呈现的 cells如下:

  
- (UITableViewCell *) tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath  {  UITableViewCell *result = nil;  if ([tableView isEqual:self.myTableView]){  static NSString *TableViewCellIdentifier = @"MyCells";  result = [tableViewdequeueReusableCellWithIdentifier:TableViewCellIdentifier];  if (result == nil) { result = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:TableViewCellIdentifier]; }  result .textLabel.text = [NSString stringWithFormat:@"Section %ld, Cell %ld",(long)indexPath.section,  (long)indexPath.row]; } return result;}
 

3、在 Table Viewscell中展示快捷菜单

你想让用户使用 App 时,只要通过一个手指放在 App 中一个 Table Viewcell 上,就能在

他们原本可选的操作中使用复制/粘贴选项。

在你的 Table View 的委托对象上实现下面 3 个 UITableViewDelegate 协议的方法:

tableView:shouldShowMenuForRowAtIndexPath:

这个方法的返回值属于 BOOL 类型。如果你从这个方法返回Yes,iOS 将为 TableViewcell 展示快捷菜单,这个 cell 的索引通过 shouldShowMenuForRowAtIndexPath 参数传递给你。

tableView:canPerformAction:forRowAtIndexPath:withSender:

这个方法的返回值也属于 BOOL 类型。一旦你允许 iOS 为 Table Viewcell 展示快捷菜单,iOS 将会多次调用这个方法,并且通过你对选择器的操作来决定是不是要展示快捷菜单。所以如果 iOS 会问你是否想要对用户显示“复制”菜单,这个方法就会在 Table View 的委托对象中调用;这个方法的 canPerformAction 参数等同于@selector(copy:).

tableView:performAction:forRowAtIndexPath:withSender:

在 Table Viewcell 的快捷菜单中一旦你允许显示特定动作,并且一旦用户从菜单中选中了这个动作时,这个方法会在 Table View 的委托对象中调用。此时,你必须采取任何满足用户需求的行动。例如,如果用户选择的“Copy”,你将需要有一个粘贴板放那些被选中的Table View 单元格的内容。

- (BOOL) tableView:(UITableView *)tableViewshouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath  {            /* Allow the context menu to be displayed on every cell */             return YES;  } - (BOOL) tableView:(UITableView *)tableViewcanPerformAction:(SEL)actionforRowAtIndexPath:(NSIndexPath*)indexPathwithSender:(id)sender  { NSLog(@"%@",NSStringFromSelector(action));  /* Allowevery action for now */ return YES; } - (void) tableView:(UITableView*)tableView performAction:(SEL)actionforRowAtIndexPath:(NSIndexPath*)indexPathwithSender:(id)sender  {  /* Empty for now */  }


4、添加和删除cell

#pragma mark - 更新tableView - (void)updateTableView {     [searchConditionTableViewbeginUpdates];     if(!isHigherSearch)     {//删除rows        [searchConditionTableView deleteRowsAtIndexPaths:[NSArrayarrayWithObjects:[NSIndexPath indexPathForRow:5 inSection:0],[NSIndexPathindexPathForRow:6 inSection:0],[NSIndexPath indexPathForRow:7inSection:0],[NSIndexPath indexPathForRow:8 inSection:0],[NSIndexPathindexPathForRow:9 inSection:0],[NSIndexPath indexPathForRow:10 inSection:0],nil] withRowAnimation:UITableViewRowAnimationAutomatic];              }     else    {//添加rows         [searchConditionTableViewinsertRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:5inSection:0],[NSIndexPath indexPathForRow:6 inSection:0],[NSIndexPathindexPathForRow:7 inSection:0],[NSIndexPath indexPathForRow:8inSection:0],[NSIndexPath indexPathForRow:9 inSection:0],[NSIndexPathindexPathForRow:10 inSection:0], nil]withRowAnimation:UITableViewRowAnimationAutomatic];     }    [searchConditionTableView endUpdates]; }


 
原创粉丝点击