美文网首页
UIKit-UITableView详解

UIKit-UITableView详解

作者: 才寒 | 来源:发表于2015-04-23 17:21 被阅读1561次

    UITableView

    一.UITableView

    <p>tableView 是项目开发里经常用到的控件,刚开始使用时可能会觉得这玩意功能强大但实现起来复杂,不过用多了,就会觉得它功能强大而且简单。
    <p>分类 tableView有两种风格,每次初始化时必须制定一种风格,默认是 Plain,而且创建成功后是不可更改的,所以希望通过一个tableView实例在两种风格之间互相切换的少年实在是想多了。
    UITableViewStylePlain:section 的headers和footers是漂浮在内容上层的,而且这种风格的列表可以在右侧有一个索引条,通过索引直接跳转到对应的section。
    UITableViewStyleGrouped:有默认的background color和background view ,iOS7之前每个分组都有圆角效果感觉挺叼,不过iOS7扁平化之后跟UITableViewStylePlain也没啥区别了,而且不能使用索引功能。
    <p>创建 tableView必须有一个协议的实现类和数据源的实现类。

        // 1.初始化plain风格的table,plain可以使用索引功能
        self.plainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 80, self.view.bounds.size.width, self.view.bounds.size.height - 80)];
        self.plainTableView.dataSource = self;//  设置数据源
        self.plainTableView.delegate = self;//  设置代理
    
        //2.实现数据源方法
        - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
          return 10;
        }
    
        - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
            static NSString *identifier = @"Cell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            return cell;
        }
    

    <p>属性 tableView通过属性设置各项数值

        self.plainTableView.tag = 10001;
        
        self.plainTableView.rowHeight = 92;//   单元格高度,优先级比                               -tableView:heightForRowAtIndexPath:低
        self.plainTableView.sectionHeaderHeight = 40;
        self.plainTableView.sectionFooterHeight = 40;
        
        self.plainTableView.estimatedRowHeight = 92;//  估算单元格高度,(iOS7)
        self.plainTableView.estimatedSectionHeaderHeight = 40;//  估算section头部视图高度,(iOS7)
        self.plainTableView.estimatedSectionFooterHeight = 40;//  估算section尾部视图高度,(iOS7)
        
        self.plainTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 20);//   分割线间隙,(iOS7)
        
        self.plainTableView.backgroundColor = [UIColor whiteColor];//  背景色
        self.plainTableView.backgroundView = nil;//  背景视图,想要显示背景视图必须先把单元格的背景色设为clearColor
    

    <p>编辑 tableView由单元格组成,每个单元格都具有选中属性,实现了tableView的单选和多选,不过tableView存在编辑模式和普通模式,所以选择也分为编辑模式下和普通模式下的单选和多选,默认只能在普通模式下单选。除此之外单元格的选中也分为多个样式:

    • UITableViewCellSelectionStyleNone
    • UITableViewCellSelectionStyleBlue
    • UITableViewCellSelectionStyleGray
    • UITableViewCellSelectionStyleDefault (iOS7)
        self.plainTableView.allowsSelection = YES;//  默认是YES,决定单元格在非编辑模式下是否可单选
        
        self.plainTableView.allowsSelectionDuringEditing = NO;//  默认是NO,决定单元格在编辑状态下是否可单选
    
        self.plainTableView.allowsMultipleSelection = NO;//  默认是NO,决定单元格在非编辑模式下是否可多选,不被allowsSelection影响
        
        self.plainTableView.allowsMultipleSelectionDuringEditing = NO;//  默认是NO,决定单元格仔编辑状态下是否可多选,当该值被设为YES时,列表的编辑模式将没有删除、添加
    

    <p>信息 tableView有许多方法获取自身的各项属性

    //  获取number
        NSInteger numOfSection = [self.plainTableView numberOfSections];
        
        NSInteger numOfRowInSection0 = [self.plainTableView numberOfRowsInSection:0];
        
        NSLog(@"%d%d",numOfSection,numOfRowInSection0);
        
        //  获取Frame
        CGRect sectionRect = [self.plainTableView rectForSection:0];//  包括section头部视图和尾部视图的
        
        CGRect headerRect = [self.plainTableView rectForHeaderInSection:0];
        
        CGRect footerRect = [self.plainTableView rectForFooterInSection:0];
        
        CGRect cellRect = [self.plainTableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        
        NSLog(@"%f%f%f%f",sectionRect.size.height,headerRect.size.height,footerRect.size.height,cellRect.size.height);
        
        //  获取indexPath
        NSIndexPath *indexPath0 = [self.plainTableView indexPathForRowAtPoint:CGPointMake(10, 200)];//  当点不在列表任意单元格中的时候返回nil
        
        NSIndexPath *indexPath1 = [self.plainTableView indexPathForCell:[self.plainTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:6 inSection:0]]];//   当单元格不可见的时候返回nil
        
        NSArray *indexPathArr0 = [self.plainTableView indexPathsForRowsInRect:CGRectMake(0, 0, 200, 0)];//  当Rect无效时返回nil
        
        NSArray *visibleArr = [self.plainTableView indexPathsForVisibleRows];
        
        NSArray *selectedArr = [self.plainTableView indexPathsForSelectedRows];
        
        //  获取Cell
        UITableViewCell *cell = [self.plainTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:10 inSection:0]];//  当单元格不可见活着indexPath超出范围时返回nil
        
        NSArray *cellArr = [self.plainTableView visibleCells];
        
        //  获取UITableViewHeaderFooterView
        UITableViewHeaderFooterView *headerView = [self.plainTableView headerViewForSection:0];//   (iOS6)
        
        UITableViewHeaderFooterView *footerView = [self.plainTableView footerViewForSection:0];//   (iOS6)
    

    <p>外观 索引样式、分割线样式、单元格样式、列表头部尾部等等

        self.plainTableView.sectionIndexMinimumDisplayRowCount = 1;// 当指定section的行数达到这个值的时候,在右侧显示该section的索引列表
        self.plainTableView.sectionIndexColor = [UIColor blackColor];// section索引的文字颜色,(iOS6)
        self.plainTableView.sectionIndexBackgroundColor = [UIColor grayColor];// 索引未被触碰时的背景颜色,(iOS7)
        self.plainTableView.sectionIndexTrackingBackgroundColor = [UIColor redColor];// 索引被触碰时的背景颜色,(iOS6)
        
        /* UITableViewCellSeparatorStyle
         * UITableViewCellSeparatorStyleNone,
         * UITableViewCellSeparatorStyleSingleLine,
         * UITableViewCellSeparatorStyleSingleLineEtched  只有group的table可以使用该样式
         */
        self.plainTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;// 现在一般都是设为UITableViewCellSeparatorStyleNone然后自定义
        self.plainTableView.separatorColor = [UIColor purpleColor];// 默认是gray
        self.plainTableView.separatorEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];// 列表分隔的样式效果,(iOS8)need to do more
        
        /*
         * 启用与iOS6,客户端可以为每一个cell注册一个nib或class
         * 如果全部重用identifiers都注册了,使用新方法-dequeueReusableCellWithIdentifier:forIndexPath:来保证一个单元格实例返回
         * 当从dequeue方法中返回实例的时候它们会重置正确的大小
         */
        [self.plainTableView registerNib:[UINib nibWithNibName:@"customCell"  bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"customCell"];//  注册自定义单元格,注册后在单元格重制方法里才能只通过Identifier就找到对应的单元格,(iOS5)
        
        //- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);
        
        //- (void)registerNib:(UINib *)nib forHeaderFooterViewReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);
        
        //- (void)registerClass:(Class)aClass forHeaderFooterViewReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);
    

    <p>方法

        //1.刷新数据
        - (void)reloadAction {
        [self.plainTableView reloadData];
    }
        //2.刷新索引
        - (void)reloadIndexTitleAction {
        [self.plainTableView reloadSectionIndexTitles];
    }
        //3.强制定位
        - (void)scrollToIndexPath {
        /* UITableViewScrollPosition的枚举
         * UITableViewScrollPositionNone
         * UITableViewScrollPositionTop
         * UITableViewScrollPositionMiddle
         * UITableViewScrollPositionBottom
         */
        [self.plainTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
    }
        //4.定位选中行
        - (void)scrollToNearestSelectedRow {
        [self.plainTableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:YES];// 定位到indexPath最小的选中单元格的位置,多选一样有效
    }
        //5.模式变换
        - (void)edit:(UIButton *)sender {
        sender.selected = !sender.selected;
        [self.plainTableView setEditing:sender.selected animated:YES];
    }
        //6.选中行并定位   
        - (void)getPlainTableViewSelection {
        NSIndexPath *indexPath = [self.plainTableView indexPathForSelectedRow];// 当有多个选中是,返回indexPath最小的那个
        
        NSArray *indexPathArr = [self.plainTableView indexPathsForSelectedRows];// (iOS5)
        
        [self.plainTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];// 选中
        
        [self.plainTableView deselectRowAtIndexPath:indexPath animated:YES];// 取消选中
    } 
    

    二.UITableView的四大功能

    <p>添加、删除

    /* 实现添加删除功能
     * 1:实现-tableView:canEditRowAtIndexPath: ,不实现时全部cell默认可编辑,该方法决定是否可编辑
     * 2.实现-tableView:commitEditingStyle:forRowAtIndexPath:,必须实现,该方法自定义添加删除功能
     * 3.实现-tableView:editingStyleForRowAtIndexPath:,不实现时为删除样式,该方法决定编辑样式
     * 4.可以实现-tableView:willBeginEditingRowAtIndexPath:
                -tableView:didEndEditingRowAtIndexPath:
         两个方法监听编辑动作并作相应自定义
     */
    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
        // 可以不实现该方法,默认全部单元格都是可编辑,也可在此处控制单元格是否可编辑
        return YES;
    }
    
    - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
        // 在这里定义添加删除功能,当添加或删除按钮被点击时,datasource必须提交更改,当edit动作使用UITableViewRowAction时,处理动作会被取代
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            [tableData removeObjectAtIndex:indexPath.row];
            [self.plainTableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
        }
        else if (editingStyle == UITableViewCellEditingStyleInsert) {
            
        }
    }
    
    - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
        /*
         * UITableViewCellEditingStyleNone
         * UITableViewCellEditingStyleDelete
         * UITableViewCellEditingStyleInsert
         */
        return UITableViewCellEditingStyleNone;
    }
    

    <p>排序

    /* 移动功能
     * 1.实现-tableView:canMoveRowAtIndexPath:,不实现时全部单元格默认可移动
     * 2.实现-tableView:moveRowAtIndexPath:toIndexPath:,必须实现,在该方法中定义移动功能,只有实现了该方法,编辑模式下才显示移动图标
     * 3.可以实现
            -tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath
       自定义某些特定功能,不过尽量还是别实现,因为这个方法cell在移动过程中每经过一个cell就会调用一次,调用地多会影响性能
     * 4.可以实现
            -tableView:willBeginEditingRowAtIndexPath:
            -tableView:didEndEditingRowAtIndexPath:
       两个方法监听编辑动作并作相应自定义
     */
    - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
        // 允许某个指定行显示复制视图,默认情况下只有datasource实现了-tableView:moveRowAtIndexPath:toIndexPath:才显示
        return YES;
    }
    
    - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
        if (sourceIndexPath != destinationIndexPath) {
            id object = [tableData objectAtIndex:sourceIndexPath.row];
            [tableData removeObjectAtIndex:sourceIndexPath.row];
            if (destinationIndexPath.row > [tableData count]) {
                [tableData addObject:object];
            }
            else {
                [tableData insertObject:object atIndex:destinationIndexPath.row];
            }
        }
    }
    

    <p>索引

    - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
        // 设置section标题的列表来显示在section索引视图上
        return @[@"a",@"a",@"a",@"a",@"a",@"a"];
    }
    
    - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
        // 告诉列表哪个section对应哪个索引
        return index;
    }
    

    <p>复制

    #pragma mark  - 复制黏贴功能
    // 三个方法必须都实现,缺一不可
    - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath {
        // 允许长按显示菜单,也可以作为cell长按手势回调
        NSLog(@"---------长按");
        return NO;
    }
    
    - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
        // 允许每一个Action
        return  YES;
    }
    
    - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender {
        // 对一个给定的行告诉代表执行复制或粘贴操作内容
        if (action==@selector(copy:)) {//如果操作为复制
            UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];//黏贴板
            [pasteBoard setString:cell.textLabel.text];
            NSLog(@"%@",pasteBoard.string);//获得剪贴板的内容
        }
    }
    

    相关文章

      网友评论

          本文标题:UIKit-UITableView详解

          本文链接:https://www.haomeiwen.com/subject/odgsfttx.html