今天看啥  ›  专栏  ›  Muen

iOS开发小技巧:tableview

Muen  · 掘金  ·  · 2021-05-08 14:51

文章预览

阅读 41

iOS开发小技巧:tableview

cell的收起、打开

www.jianshu.com/p/202b5cfcc…

自定义cell选中时的背景色

cell.selectedBackgroundView = [UIView new];  
cell.selectedBackgroundView.backgroundColor = [UIColor xxxxxx];  
复制代码

刷新某个cell或section

NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];

NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:2];    
[tableview reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];    

复制代码

判断某行cell是否已经显示

CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath];
BOOL completelyVisible = CGRectContainsRect(tableView.bounds, cellRect);
复制代码

判断cell在屏幕上

1.-(NSArray*)visibleCells; UITableView的方法,这个最直接,返回一个UITableviewcell的数组。 对于自定制的cell,之后的处理可能稍微繁琐些。

2.- (NSArray*)indexPathsForVisibleRows; UITableview的又一个方法,这个比较好用,返回一个NSIndexPath的数组,可以直接用indexpath.row去调你的table_related_Array里的数据了。比较方便,用于自定制的cell。

3.这个方法可以用在代理回调较多的设计中

- (CGRect)rectForRowAtIndexPath:(NSIndexPath*)indexPath;
CGRect cellR = [myTV rectForRowAtIndexPath:indx];
if (myTV.contentOffset.y - cellR.origin.y < myCell.frame.size.height || cellR.origin.y - myTV.contentOffset.y >myTV.size.height) {
    //这时myCell不在myTV的可视区域了。

} else {
    //myCell在可视区域,业务处理

}
复制代码

加载网络图片优化

思想:停止滚动时才加载 来自www.jianshu.com/p/328e50390… 个人认为需求不适合

某个cell

UITableViewCell *cell = [weakSelf.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];

或

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

   if (scrollView == _rightTableView && _isSelected == NO) {
       //系统方法返回处于tableView某坐标处的cell的indexPath
        NSIndexPath * indexPath = [_rightTableView indexPathForRowAtPoint:scrollView.contentOffset];
        NSLog(@"滑到了第 %ld 组 %ld个",indexPath.section, indexPath.row);
        _currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.section];
        [_leftTableView reloadData];
        [_leftTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:indexPath.section] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
    }

}
复制代码

自定义cell的右icon

self.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"对号"]];
// 好处:无需再次布局
复制代码

点击cell的子控件,获取对应的cell

CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];

UITableViewCell *cell = (UITableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
复制代码

选中滚动到某行cell

[self.myTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
复制代码

默认选中某行cell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PDNetCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PDNetCell" forIndexPath:indexPath];
    cell.model = [self.gridArr objectAtIndex:indexPath.row];
    
    // 默认选中行( 关键代码 )
    if (!isInit) {
        NSIndexPath *firstPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [tableView selectRowAtIndexPath:firstPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        if ([tableView.delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:)]) {
            [tableView.delegate tableView:tableView didSelectRowAtIndexPath:firstPath];
        }
        isInit = YES;    //  标志,只能默认点击一次
    }
    
    return cell;
}


// 在cell.m文件中方法,显示选中样式
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

//.......
}
复制代码

选中cell时的样式

//无色  
cell.selectionStyle = UITableViewCellSelectionStyleNone;  
//蓝色  
cell.selectionStyle = UITableViewCellSelectionStyleBlue;  
//灰色  
cell.selectionStyle = UITableViewCellSelectionStyleGray;
复制代码

设置cell之间的间距

//自定义cell,重写setFrame:方法
- (void)setFrame:(CGRect)frame
{
    frame.size.height -= 20;
    [super setFrame:frame];
}
复制代码

插入数据

       NSMutableArray *insertion = [NSMutableArray arrayWithCapacity:0];
       for (int i = 0; i < tmpGoodsList.goods.count; i++) {
          [insertion addObject:[NSIndexPath indexPathForRow:tmpcount + i inSection:3]];
       }
            
       [self.rushTableView insertRowsAtIndexPaths:insertion withRowAnimation:UITableViewRowAnimationMiddle];
复制代码

数据未显示满一屏幕,隐藏多余的Cell

self.tableView.tableFooterView = [[UIView alloc]init];

复制代码

分割线设置为顶格(默认开头空15像素点)

www.titanjun.top/2016/11/20/…

 cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
复制代码

滚动到某行

[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:NSNotFound inSection:2] atScrollPosition:UITableViewScrollPositionTop animated:YES];
复制代码

点击cell自动滚到下一行

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//第一种方法
[tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
//第二种方法
[self.tableVieW selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
}
复制代码

更新行高

  1. cell中添加一个属性

@property(nonatomic,assign)float cellH;

2.设置block回调,用于刷新行高 @property(nonatomic,strong)void(^heightReback_Block)(float cellH);

3.调用block,开始刷新

    cell.heightReback_Block = ^(float cellH) {
        _cellH = cellH;   //  更新行高
        [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationBottom];
    };

·······

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return _cellH;
}
复制代码

cell高度自适应1 *

// 实现代理方法 即可
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
//  注:cell子控件的布局 !
复制代码

cell高度自适应2

用frame布局时,这种通常在你的模型中添加一个辅助属性cellHeight,在模型中重写这个属性的get方法,根据你的布局和模型中的其他属性值计算出总高度。最后在tableView:heightForRow方法中,根据indexPath找出对应的模型,返回这个高度即可。

cell高度自适应3 *

    // 预估行高
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 150;
...

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || indexPath.section == 1) {
            return 81;
    }
    // 解决固定行高和系统自动计算行高  其他组走系统自动计算行高
    return UITableViewAutomaticDimension;
}
复制代码

自己缓存cell高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    BSQuestionsModel * model = _dataArray[indexPath.section];
    return model.cell_height?:UITableViewAutomaticDimension;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BSQuestionsModel * model = _dataArray[indexPath.section];
    BSQuestionsTableViewCell * cell = [BSQuestionsTableViewCell cellForTableView:tableView model:model];

    //高度缓存
    CGFloat height = [cell systemLayoutSizeFittingSize:CGSizeMake(tableView.frame.size.width, 0) withHorizontalFittingPriority:UILayoutPriorityRequired verticalFittingPriority:UILayoutPriorityFittingSizeLevel].height;
    model.cell_height = height;

    return cell;
}
复制代码

编辑状态下可多选

   
    self.myTableView.allowsMultipleSelectionDuringEditing = YES;
复制代码
- (IBAction)edit:(id)sender {    
    [self.myTableView setEditing:!self.myTableView.isEditing animated:YES];    //进入批量编辑状态
    self.deleteBtn.hidden = !self.myTableView.isEditing;
}
复制代码
- (IBAction)delete:(id)sender {
    NSMutableArray *deleArr = [NSMutableArray array];
    for(NSIndexPath *indx in self.myTableView.indexPathsForSelectedRows){
        [deleArr addObject:self.girlArray[indx.row]];    //拿到选中的行
    }
    [self.girlArray removeObjectsInArray:deleArr];    //从模型中把它们删除
    
//    [self.myTableView reloadData];   //刷新数据
    //动画刷新数据
    [self.myTableView deleteRowsAtIndexPaths:self.myTableView.indexPathsForSelectedRows withRowAnimation:UITableViewRowAnimationAutomatic];
}
复制代码

滚动到某一行cell

[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:NSNotFound inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
复制代码

下拉放大header图片

第三方:github.com/iThinkerYZ/… 1.创建tableview

。。。
//注意设置四周间距(上左下右)
self.tableView.contentInset = UIEdgeInsetsMake(0.2*screenH, 0, 0, 0);
复制代码

2.创建图片img view

    UIImageView *iimgv = [[UIImageView alloc] initWithFrame:
                    CGRectMake(0, -0.2*screenH , screenW, 0.2*screenH)];      // 0.2*screenH为图片原始高度
    iimgv.image = [UIImage imageNamed:@"myHeader"];
    iimgv.contentMode = UIViewContentModeScaleAspectFill;     //关键
    
    [self.tableView addSubview:iimgv];    //添加
    self.iimgv = iimgv;
复制代码

3.下拉放大处理

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat y = self.tableView.contentOffset.y;
    
    if (y < -0.234*screenH) {
        CGRect frame = self.iimgv.frame;
        frame.origin.y = y;
        frame.size.height = - y;
        self.iimgv.frame = frame;
    }
    return;
 
}
复制代码

4.scrollview中同样适用。

抽象基类

设计同model、同逻辑的多种cell www.jianshu.com/p/f308c43fb…

………………………………

原文地址:访问原文地址
快照地址: 访问文章快照
总结与预览地址:访问总结与预览