美文网首页iOS常用
iOS 多个分区的tableView设置每个分区第一行和最后一行

iOS 多个分区的tableView设置每个分区第一行和最后一行

作者: 浅浅_e90e | 来源:发表于2021-01-11 15:32 被阅读0次

    现在出现很多那种分区的tableView,每个分区的第一行和最后一行是圆角的,中间行没有圆角效果,如下图所示的效果:


    image.png

    分情况处理:
    情况一:iOS版本在iOS13及以上版本
    创建UITableView的时候,直接运用 UITableViewStyleInsetGrouped 枚举值就可以实现这个效果。

    if (@available(iOS 13.0, *)) {
            self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, navigationHeight, ScreenWith, ScreenHeight-navigationHeight) style:UITableViewStyleInsetGrouped];
        } else {
            // Fallback on earlier versions
            self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, navigationHeight, ScreenWith, ScreenHeight-navigationHeight) style:UITableViewStyleGrouped];
        }
    

    其他部分,包括自定义cell的样式都正常写即可,注意,cell的底部view不用两边留边距,直接设置与屏幕宽相等就行。

    情况二:iOS版本小于iOS13的
    有一个比较简单的实现方法:在自定义的cell中创建3个UIView来辅助实现,一个topView,设置背景色为白色,一个bottomView,设置背景色为白色,一个centerView,设置背景色为白色。

        topView = [[UIView alloc] init];
        topView.backgroundColor = [UIColor whiteColor];
        [self.contentView addSubview:topView];
    
        bottomView = [[UIView alloc] init];
        bottomView.backgroundColor = [UIColor whiteColor];
        [self.contentView addSubview:bottomView];
        
         centerView = [[UIView alloc] init];
        centerView.layer.cornerRadius = 4;
        centerView.clipsToBounds = YES;
        centerView.backgroundColor = [UIColor whiteColor];
        [self.contentView centerView];
    

    将centerView的高度设置的与contentView的高度一致,并在四个边角设置好圆角效果,topView放在最上面,顶部挨着contentView的顶部,高度可以设置小一点,我设置的是10,bottomView放在最下面,底部挨着contentView的底部,高度也设置的是10,还有三个view的创建添加顺序一定是centerView在最上面。

    ⚠️注意:此时cell里的topView、bottomView、centerView需要两边留出边距,我一般设置为10,整体宽度为屏幕宽度减去20,这个看个人需求。如果两种情况都共用同一个cell,在这个自定义cell里设置子控件的frame时也需要判断iOS系统版本,确保系统版本跟样式设置方式保持一致!!

    在cell的.h文件公开一个方法来设置圆角效果

    - (void)refreshCell:(BOOL)isFirst lastCell:(BOOL)isLast;
    

    在.m文件中实现方法

    - (void)refreshCell:(BOOL)isFirst lastCell:(BOOL)isLast {
        topView.hidden = isLast;
        bottomView.hidden = isFirst;
    }
    

    在cell的代理方法cellForRow里,用cell对象调用这个方法
    第一行[cell refreshCell:NO lastCell:YES];
    最后一行[cell refreshCell:YES lastCell:NO];

    相关文章

      网友评论

        本文标题:iOS 多个分区的tableView设置每个分区第一行和最后一行

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