day08 - UITableView-02模型优化

UITableView-01基本使用

  • 直接添加数据,需要多个if,else...的判断,特别的繁琐.
  • 使用数组+字典来存放数据,拼写错误时,很难发现.
  • 使用模型来存放数据,无繁琐的判断,没有拼写错误的情况.
    步骤如下:
    1. 将每组数据,都用一个组模型来存放.

      • 组模型里面有个数组, 专门存放产品模型 (也叫模型嵌套)
    2. 多组数据形成的多个组模型,存放在一个大的数组里.

    @implementation Car
     + (instancetype)carWithIcon:(NSString *)icon name:(NSString *)name{
        Car *car = [[self alloc]init];
        car.icon = icon;
        car.name = name;
        return car;
    }
    @end
    
    @property (nonatomic ,strong) NSArray *carData;
    
    -(NSArray *)carData{
      if(_carData == nil){
        CarGroup *dgGroup = [[CarGroup alloc]init];
        dgGroup.headInfo = @"德国系列";
        dgGroup.endInfo = @"你瞅啥...";
        dgGroup.cars = @[
                          [Car carWithIcon:@"m_2_100"name:@"奔驰"],
                          [Car carWithIcon:@"m_3_100" name:@"宝马"]
                         ];
    ......
        self.carData = @[dgGroup]; //多个组模型存放在一个大的数组里
    }
    return _carData;
    }
    
    1. 获取对应的数据.
     //有多少组,默认为1组
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
      return self.carData.count;
    }
    //每组有多少行数据. (Section -当前组)
    - (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        CarGroup *group = self.carData[section];
        return group.cars.count;
      }
    
    //每行显示的内容
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        UITableViewCell *cellTemp = [[UITableViewCell alloc]init];
        CarGroup * group = self.carData[indexPath.section]; // 获取对应组.
        Car *carTemp = group.cars[indexPath.row]; //当前组里面的对应行
        cellTemp.textLabel.text = carTemp.name;
        cellTemp.imageView.image = [UIImage  imageNamed:carTemp.icon];
        return cellTemp;
    }
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 掌握 设置UITableView的dataSource、delegate UITableView多组数据和单组数据...
    JonesCxy阅读 4,980评论 0 2
  • *7月8日上午 N:Block :跟一个函数块差不多,会对里面所有的内容的引用计数+1,想要解决就用__block...
    炙冰阅读 7,346评论 1 14
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 13,849评论 1 32
  • 版权声明:未经本人允许,禁止转载. 1. TableView初始化 1.UITableView有两种风格:UITa...
    萧雪痕阅读 7,910评论 2 10
  • 一个女人想要俘获男人的钱包,而不是他那颗心,这个女人终究会是男人金钱下使唤的奴隶,更有可能沦落为他的泄欲工具。女人...
    佛天女巫阅读 3,602评论 5 18