黑马程序员技术交流社区
标题:
UITableView小例子的实现
[打印本页]
作者:
yuanlingqi
时间:
2014-12-2 23:07
标题:
UITableView小例子的实现
本帖最后由 yuanlingqi 于 2014-12-2 23:18 编辑
UITableView的使用完全依赖于代理模式的实现。视频中,李老师选择了较为复杂和浪费内存空间的方式来实现了打钩处理,
具体就是使用了一个数组来存放选中元素,然后在加载cell时候,判断元素是否被已选对象数组包含,来进行打钩处理。
猜测李老师之所以选择这种较纠结实现方式来讲解,是为了更好的锻炼学员的思路,的确用心良苦。
较好的打钩实现方式当然是增加对象属性了,根据属性来决定是否已打钩,本例子就使用了增加属性的打钩方式,
并实现了点一次打钩,再点则去除打钩的逻辑,不多说,上代码。
//
// CJPViewController.m
// tableView性能优化
//
// Created by lucky on 14/12/1.
// Copyright (c) 2014年 cn.itcast. All rights reserved.
//
#import "CJPViewController.h"
#import "Shop.h"
@interface CJPViewController ()<UITableViewDataSource,UITableViewDelegate>{
NSMutableArray *shopArray;
}
@end
@implementation CJPViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//获取字典文件路径
NSString *path = [[NSBundle mainBundle]pathForResource:@"shops.plist" ofType:nil];
//读取文件
NSArray *array = [NSArray arrayWithContentsOfFile:path];
//实例化对象数组
shopArray = [NSMutableArray array];
//声明临时变量
Shop *shop;
//将字典对象模型化
for (NSDictionary *dic in array) {
shop = [Shop shopWithDictionary:dic];
[shopArray addObject:shop];
}
}
#pragma mark 指定section的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return shopArray.count;
}
#pragma 加载每行数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//1.定义标识
static NSString *id = @"mycell";
//2.从缓存池中获取cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:id];
//3.若为空则创建实例
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:id];
}
//4.显示商品
Shop *s = shopArray[indexPath.row];
//设置名称
cell.textLabel.text = s.name;
//设置描述
cell.detailTextLabel.text = s.desc;
//设置图片
cell.imageView.image = [UIImage imageNamed:s.icon];
//若曾被选中,则打钩,否则去除标记
if (s.gou == YES) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
#pragma mark 设定行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 70;
}
#pragma mark 选中方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(@"-----%d",indexPath.row);
//去除选中状态
[tableView deselectRowAtIndexPath:indexPath animated:YES];
//设置打钩的值
Shop *s = shopArray[indexPath.row];
//若已经打钩则去除打钩,若未打钩则打钩
s.gou = s.gou ==YES?NO:YES;
//替换数据源中的对象
[shopArray replaceObjectAtIndex:indexPath.row withObject:s];
//刷新数据
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:(UITableViewRowAnimationAutomatic)];
}
@end
复制代码
aaa.png
(66.63 KB, 下载次数: 12)
下载附件
2014-12-2 23:18 上传
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2