美文网首页
storyboard中加载自定义cell

storyboard中加载自定义cell

作者: H小凡 | 来源:发表于2017-01-05 12:41 被阅读1000次

从storyboard中加载cell
1.往storyboard中拖入相关的控件 如图

屏幕快照 2017-01-05 下午12.10.25.png
tableView控件右键delegate和dataSource与控制器关联

2新建一个类TableViewCell继承UITableViewCell,定义两个属性与storyboard中两个控件相对应 如图 此时还是未关联状态


屏幕快照 2017-01-05 下午12.15.08.png

3.回到storyboard,点击Table View Cell设置identifier:a , class设置为TableViewCell。
右键Table View Cell 将里面的img和label(在TableViewCell中定义的两个属性)与控件关联起来 如图


屏幕快照 2017-01-05 下午12.22.14.png

4.相关代码
导入TableViewCell类,添加协议,定义一个数组

#import "ViewController.h"
#import "TableViewCell.h"
@interface ViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) NSArray *array;
@end

解析plist文件的关键步骤就在这里了

-(NSArray *)array {
    if (!_array) {
        //创建可变数组用来接收遍历的字典数据
        NSMutableArray *mutableArr = [NSMutableArray array];
        //读取plist到arr中
        NSString *path = [[NSBundle mainBundle] pathForResource:@"abc.plist" ofType:nil];
        NSArray *arr = [NSArray arrayWithContentsOfFile:path];
        //遍历数组arr
        for (NSDictionary *dict in arr) {
            //字典添加到可变数组
            [mutableArr addObject:dict];
        }
        //赋值给成员变量数组
        _array = mutableArr;
    }
    //返回数组
    return _array;
}

自定义cell

//设置组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//设置行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count;
}

//设置cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //用TableViewCell这个类创建一个cell,Identifier和刚刚在storyboard中设置的一样
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"a"];
    if (!cell) {
        cell = [[TableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"a"];
    }
    //自定义cell里面的几个控件内容,self.array[indexPath.row]是一个字典
    cell.label.text = [self.array[indexPath.row] objectForKey:@"text"];
    cell.img.image = [UIImage imageNamed:[self.array[indexPath.row] objectForKey:@"icon"]];
    return cell;
}

plist内容


屏幕快照 2017-01-05 下午12.39.04.png

最终效果图


b.gif

相关文章

网友评论

      本文标题:storyboard中加载自定义cell

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