今天项目中,要用tableview做成一个折叠效果,不过要的效果特别简单,去网上搜了一下,实现都不那么简单,为了这么简单的一个效果去写那么多代码,感觉特别亏,于是我就想能不能有个简单的方法,能不能用layer的masksToBounds这个属性去实现呢?masksToBounds的作用是把超出自己bounds的子控件剪掉。我先把cell的内容全部加载上去,然后用masksToBounds把第二层显示的东西剪掉,等我点击的时候,改变cell的大小,被剪掉的东西就由出来了,心动不如行动,代码撸起。
- (void)viewDidLoad {
[super viewDidLoad];
UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
tableView.dataSource = self;
tableView.rowHeight = 30;
tableView.delegate = self;
[self.view addSubview:tableView];
//用来存放一点开的数组
_array = [NSMutableArray array];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//已点开的cell高度变高
if ([_array containsObject:indexPath]) {
return 60;
}
return 30;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 40;
}
<pre name="code" class="objc">-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *identifier = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
//添加cell上的内容
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, cell.frame.size.width, 30)];
label.tag = 10;
[cell.contentView addSubview:label];
//设置masksToBounds为YES
cell.layer.masksToBounds = YES;
//设置内层label上的内容
UILabel *infoLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, cell.frame.size.width, 30)];
infoLabel.tag = 20;
[cell.contentView addSubview:infoLabel];
}
//为cell上的控件赋值
UILabel *label = (UILabel *)[cell viewWithTag:10];
label.text = [NSString stringWithFormat:@"我是第%ld个",indexPath.row];
UILabel *infoLabel = (UILabel *)[cell viewWithTag:20];
infoLabel.text = [NSString stringWithFormat:@"我是内层的第%ld个",indexPath.row];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//判断是否已经点开,若点开,则删除,未点开添加
if ([_array containsObject:indexPath]) {
[_array removeObject:indexPath];
}else{
[_array addObject:indexPath];
}
NSLog(@"%ld",(long)indexPath.row);
//刷新tableView
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}