ios学习之(四)表视图的应用及增,删,改,查

本文深入探讨了iOS应用中表视图的使用方法,包括如何创建、配置和编辑表视图,实现数据的移动、修改、删除及添加,并提供了自定义单元格的实例,帮助开发者掌握表视图的高级应用。
表视图用于显示数据列表。  表视图限制- –支持多行,但只有一列(tableView是为手持设备所设计)
两种类型:style
    a 分组表---如微博视图等效果
    b 无格式表,平铺型(Plain)---如系统自带的设置效果
eg:
   //创建UITableView,两种类型UITableViewStylePlain
                            UITableViewStyleGrouped
   UITableView *myTable = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    myTable.delegate = self;    //获取外观数据
    myTable.dataSource = self;  //获得内容数据
    [self.view addSubview:myTable];
    [myTable release];

在.h中提供协议,表视图是个空容器
<UITableViewDataSource,UITabBarDelegate>
           eg:Section分区: 表中的每一个组
       //设置包含的section分区
 -(NSInteger)numberOfSectionsInTableView: (UITableView *)tableView
 {
    return 分区数;
 }
              Row行:为基本单位
            //设置section的行数
 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
 {
    return 行数;
 }
           单元格--单元格为基本元素,填充内容数据
           //设置单元格的内容
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
    //标记符,用来标记创建的cell
    static NSString *cellstr = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cellstr]; 
   //根据复用标示获取复用的单元格对象
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellstr];
    }
 //创建单元格,类型
  * UITableViewCellStyleSubtitle--显示:图片--文本-
                                        detailTextLabel(位置正下方)
  * UITableViewCellStyleDefault--显示:图片-文本
     *  UITableViewCellStyleValue1-- 显示:图片-文本-detailTextLabel(位置加后面)
  * UITableViewCellStyleValue2--显示:detailTextLabel(位置加前面)-图片-文本
  * //设置字体的大小
    cell.textLabel.font = [UIFont boldSystemFontOfSize:字体大小];
    cell.textLabel.text = @“文本”;
    cell.imageView.image = [UIImage imageNamed:@“图片”];
    cell.detailTextLabel.text = @“详情文本”;
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
   // UITableViewCellAccessoryDetailDisclosureButton--- >
     UITableViewCellAccessoryCheckmark  ----------打勾
     UITableViewCellAccessoryDisclosureIndicator ----->
     UITableViewCellAccessoryNone --------------空
   //
   //字典的显示方法
    NSArray *keys = [self.dict allKeys];
    NSArray *temp = [keys sortedArrayUsingSelector:@selector(compare:)];
    NSString *keyString = temp[indexPath.section];
    NSArray *values = [self.dict objectForKey:keyString];
    cell.textLabel.text = values[indexPath.row];
    //
     return cell;
}
//设置行的高度: heightForRow……………….
//设置section,Header,Footer
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return 头文字;
}
//设置是否可以编辑
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
    return YES;
 }
//单元格点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}
//设置缩进级别
-(NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 整数;
}

 创建单选的基本原理
               创建一个NSIndexPath属性,记录当前选中行的IndexPath
               判断要显示的行是否与当前的选中行是同一行。若是,则选中;若否,则不选中
               单击某行时更改属性的值,并且刷新有关行



定制表视图单元格
 1.单元格创建时定制:
   eg:
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) 
      {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
      //定制单元格
         UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5580120)];
         imageView.tag = 11;
         [cell.contentView addSubview:imageView];
         [imageView release];
      }
    UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:11];
    imageView.image = 数据源;

      return cell;
}

 2.使用UITabelViewCell子类进行定制
   创建类继承于UITableViewCell,
eg:在类中重新初始化单元格,假设类名为MyCell
  -(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        //定制单元格
           UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 80, 120)];
           imageView.tag = 11;
          [self.contentView addSubview:imageView];
          self.portraitView = imageView;
         [imageView release];
    }
    return self;
}
//------------------//
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    MyCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) 
      {
        cell = [[MyCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
      }

      return cell;
}

 3.使用Nib文件进行定制:
   创建User Interface -- Empty--拉一个表视图单元格--初始化单元格内容(CustomCell.xib)
  -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CellIdentifier;  //设置自定义表视图单元格的身份,在属性:
    static BOOL isRegister = NO;
    if(!isRegister)
     {
        UINib *nib = [UINib nibWithNibName:@“CustomCell” bundle:[NSBundle mainBundle]];
        [tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
        isRegister = YES;
     }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:11];
    imageView.image = 数据源;
      return cell;
}
 4.数据绑定原则:
   
 5.结合使用:


表视图的数据编辑
  1.表视图的编辑状态:
   // 创建按钮表示是否进入编辑
 -(void)editButtonPressed
  {
      [self.tableView setEditing:!self.tableView.editing animated:YES];
   }
 //设置编辑状态
 -(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
 {
    return UITableViewCellEditingStyleDelete
    //
      UITableViewCellEditingStyleDelete  //默认--编辑风格--删除
      UITableViewCellEditingStyleInsert //添加
      UITableViewCellEditingStyleNone
      UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert
   //
 }
2.插入:
 //指定编辑风格UITableViewCellEditingStyleInsert
 -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
 //可弹到另一页面指定详细信息,这里写死
    Student *stuToInsert = [[Student alloc]init];
        stuToInsert.name = @"新添加的行";
        [self.list insertObject:stuToInsert atIndex:indexPath.row];
        [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
3.删除:
 -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {   //因执行插入操作时也会触发该方法,if判断是否删除
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self.list removeObjectAtIndex:indexPath.row]; //删除数组
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];   //刷新
    }
 }

4.实现表视图数据的移动:
 //实现表视图的移动
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
    NSUInteger fromRow = sourceIndexPath.row;//要移动的行
    NSUInteger toRow = destinationIndexPath.row;//接受插入的行
    id object = [self.list objectAtIndex:fromRow];
    [self.list removeObjectAtIndex:fromRow];
    [self.list insertObject:object atIndex:toRow];
}
5.实现表视图数据的修改:(委托方法实现)



表视图的索引,索引是基于分组数据的
字母索引的实现:
eg:
 -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
 {
    return self.keys;//所有组的标题放到数组中,做为返回值,这些标题将成为创建索引的依据
 }
汉字索引的实现:
eg:
    //创建26个可变数组
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    for (char character = 'a'; character <= 'z'; character++) 
       {
          NSMutableArray *array = [[NSMutableArray alloc]init];
         [dic setObject:array forKey:[NSString stringWithFormat:@"%c",character]];
         [array release];
         [self.keys addObject:[NSString stringWithFormat:@"%c",character]];
    }
    //将没有数据的首字母去掉
    for (char character = 'a'; character <= 'z'; character++) {
        NSString *key = [NSString stringWithFormat:@"%c",character];
        NSArray *array = [dic objectForKey:key];
        if (!array.count) {
            [dic removeObjectForKey:key];
        }
    }
    //将字典中的对象排序后赋值给数组
    self.mArray = [dic.allKeys sortedArrayUsingSelector:@selector(compare:)];
    //从数组中遍历数组对象
    for (NSString *city in cities) {
        //从数组对象中获取首字符串的首字母拼音
        NSString *initial = [NSString stringWithFormat:@"%c",pinyinFirstLetter([city characterAtIndex:0])];
        //通过字典的健值获取其对象
        NSMutableArray *array = [dic objectForKey:initial];
       //可变数组没有分配空间,而是和字典公用一块空间,而可变数组只是相应字典对象的别名
        [array addObject:city];
    }
 //将创建的字母系列放在表视图的右边区
 -(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
 {
    return self.keys;
 }

注意:开启图片点击事件:
eg:self.myHead.userInteractionEnabled=YES;//开启图片点击,myHead是imageView的图片
    //创建单击手势
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(xt:)];
    //给图片添加单击手势
    [self.myHead addGestureRecognizer:tap];
设置代理<UIImagePickerControllerDelegate>
-(void) xt:(id)sender{
    UIImagePickerController *img=[[UIImagePickerController alloc]init];//图片加载
      //检查用户是否有相片库
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {       img.sourceType=UIImagePickerControllerSourceTypePhotoLibrary; //现有的图片库
               
        img.delegate=self;
        [self presentViewController:img animated:YES completion:nil];//推出了图像选择视图
    }
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *temp=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.myHead.image=temp;
    //收起视图
    [picker dismissViewControllerAnimated:YES completion:nil];
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值