客户端开发,UI设计师总是会设计出一些完美的视觉,但有些完美视觉效果需要特别的处理。前两年总听到一句话:一个漂亮的界面背后总是有一堆肮脏的代码。
先看一个有问题的效果。小图cell和大图cell之间的margin是12.5p,而两个小图cell之间的margin是25p.这是因为。cell的contentView在cell中是居中的,上下margin都是12.5。最终是这个效果:
然后UI要求每个cell之间的margin都是25p。由于大图cell和小图cell是两个不同cell模板。所以程序员第一反应是对小图cell进行特殊处理。比如特殊的插入绿色部分(如图)
那么,如何去实现这个效果呢?
首先想到是:获取cell上下情况。
1. 如果小图cell的上一个是大图cell。如果小图cell下一个是那么大图cell。cell的高度加12.5
2. 对小图contentView的top进行设置,要么是12.5.要么是0.
这两个配合,应该可以达到这个效果,但是经过尝试后。发现无法直接对contentView的frame进行设置。后来,尝试增加一层myContentView。即原先是:contentView->cell元素。改为contentView->myContentView->cell元素.然后对myContentView的frame进行设置
代码如下:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { CGFloat height = 44; if(columnItem.templateInfo.templateID == SVTemplate_301){ /*判断小图cell的顶部和底部是不是大图模板,需要增加高度*/ NSInteger preSection = (indexPath.section - 1); if ([self.viewModel columnItemForSection:preSection].templateInfo.templateID == SVTemplate_302) { height += [FSChannelCell heightOffset]; } preSection = (indexPath.section + 1); if ([self.viewModel columnItemForSection:preSection].templateInfo.templateID == SVTemplate_302) { height += [FSChannelCell heightOffset]; } } return height; } - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)_cell forRowAtIndexPath:(NSIndexPath *)indexPath{ /*判断小图cell的顶部和底部是不是大图模板,需要改变cell.contentview的位置*/ NSNull *top = nil; NSNull *bottom = nil; NSInteger preSection = (indexPath.section - 1); if (preSection >= 0 && [self.viewModel columnItemForSection:preSection].templateID == bigImage) { top = [NSNull new]; } preSection = (indexPath.section + 1); if (preSection >= 0 && [self.viewModel columnItemForSection:preSection].templateID == bigImage) { bottom = [NSNull new]; } [_cell performSelector:@selector(setContentViewTopInset:bottomInset:) withObject:top withObject:bottom]; } cell部分代码 -(instancetype) initWithColumn{ self.myContentView = [[UIView alloc]init]; [self.contentView addSubview:self.myContentView]; [self.myContentView addSubview:self.portrait]; [self.myContentView addSubview:self.videoLength]; [self.myContentView addSubview:self.contentTitle]; [self.myContentView addSubview:self.playIcon]; [self.myContentView addSubview:self.playCount]; [self.myContentView addSubview:self.account]; [self.myContentView addSubview:self.topIcon]; [self.myContentView addSubview:self.moreBtn]; return self; } -(void) setContentViewTopInset:(id)objectTop bottomInset:(id)objectBottom{ [self.myContentView mas_updateConstraints:^(MASConstraintMaker *make) { make.top.equalTo(self.contentView).offset(objectTop ? topMargin:0); make.bottom.equalTo(self.contentView).offset(objectBottom ? -topMargin:0); }]; } - (void)addConstraints { [self.myContentView mas_makeConstraints:^(MASConstraintMaker *make) { make.left.top.right.bottom.equalTo(self.contentView); }]; /*其他约束*/ } 总体来说,还是需要controller和cell配合实现这个效果。但是,也可以通过插入空cell来实现,但是那样会改变数据结构,笔者并没有使用改变数据结构的办法