UI014: UITableView 加载plist中数据显示

//  CZGroup.h
//  UITableView02
//
//  Created by qi tan on 2023/5/29.
//
#import <Foundation/Foundation.h>

@interface CZGroup : NSObject
@property(nonatomic,copy)NSString *title;
@property(nonatomic,copy)NSString *desc;
@property(nonatomic,strong)NSArray *cars;

-(instancetype)initWithDict:(NSDictionary *)dict;
+(instancetype)groupWithDict:(NSDictionary *)dict;
@end

//
//  CZGroup.m
//  UITableView02
//  Created by qi tan on 2023/5/29.

#import "CZGroup.h"

@implementation CZGroup
- (instancetype)initWithDict:(NSDictionary *)dict
{
    if(self = [super init]) {
        // self.title = dict[@"title"];
        // KVC
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}
+(instancetype)groupWithDict:(NSDictionary *)dict
{
    return [[self alloc] initWithDict:dict];
}
@end
//
//  ViewController.m
//  UITableView02
//
//  Created by qi tan on 2023/5/29.
//

#import "ViewController.h"
#import "CZGroup.h"

@interface ViewController () <UITableViewDataSource>
@property(nonatomic,strong)NSArray *groups; // 数据源
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end

@implementation ViewController
#pragma mark - 懒加载数据
-(NSArray *)groups
{
    if(_groups == nil){
        NSString *path = [[NSBundle mainBundle] pathForResource:@"cars_simple.plist" ofType:nil];
        NSArray *arrayDict = [NSArray arrayWithContentsOfFile:path] ;
        NSMutableArray * arrayM = [NSMutableArray array];
        for (NSDictionary* dict in arrayDict) {
            CZGroup *model = [CZGroup groupWithDict:dict];
            [arrayM addObject:model];
        }
        _groups = arrayM;
    }
    return _groups;
}

#pragma mark - 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.groups.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CZGroup *group = self.groups[section];
    return group.cars.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CZGroup *group = self.groups[indexPath.section];
    NSString *name = group.cars[indexPath.row];
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                                   reuseIdentifier:nil];
    cell.textLabel.text = name;
    return cell;
}
#pragma mark - 分组信息的方法
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    CZGroup *group = self.groups[section];
    return group.title;
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    CZGroup *group = self.groups[section];
    return group.desc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.dataSource = self;
}
@end


©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容