毫无疑问,有几种方法可以做到这一点。途中涉及将该图像放在第一个单元格内,这将与您的数据的其他单元格不同。当您滚动时,该图像在单元格中的位置将向下移动,这会使该图像看起来被下面的单元格覆盖。下面的代码显示了如何做到这一点(我从另一个项目中修改了这个,该项目有交替的行,似乎浮动在固定图像上)。
@interface TableController ()
@property (strong,nonatomic) NSArray *theData;
@end
@implementation TableController
- (void)viewDidLoad {
[super viewDidLoad];
self.theData = @[@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven",@"Eight",@"Nine",@"Black",@"Brown",@"Red",@"Orange",@"Yellow",@"Green",@"Blue"];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
RDCell *topCell = (RDCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
[topCell updateImageViewWithOffset:scrollView.contentOffset.y];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.theData.count + 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat height = (indexPath.row == 0)? 140 : 44;
return height;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 0) {
RDCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ImageCell" forIndexPath:indexPath];
return cell;
}else{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.textLabel.text = self.theData[indexPath.row - 1];
return cell;
}
}
自定义单元格中的代码就是这一种方法,
-(void)updateImageViewWithOffset:(CGFloat) offset {
CGFloat cellY = self.frame.origin.y;
self.topCon.constant = offset - cellY;
}
topCon 是 NSLayoutConstraint 的 IBOutlet,位于单元格顶部和单元格中图像视图的顶部之间——重要的是图像视图对单元格的顶部和侧面有约束,以及高度约束(等于单元格的高度),但对单元格的底部没有限制。如果你想看看这种方法是否能给你想要的外观,你可以从这里下载示例项目,http://jmp.sh/zOVz6Ev。