如何使用不透明的主体为UITableView Header设置清晰的背景

And*_*oss 4 uitableview ios nstableheaderview

如何使tableHeaderView 的背景清晰,但保持UITableView背景的其余部分不透明

我正在使用透明tableHeaderView来实现paralax效果.tableView后面的对象比clear tableHeaderView"窗口"长,所以我可以将可见数据居中.这适用于较长的列表,因为我可以使用tableView作为掩码,但是当我在表中没有足够的单元格时,背景对象显示在单元格下方.

相关代码:

self.tableView.backgroundView = nil;
self.tableView.backgroundColor = [UIColor whiteColor];

UIView *tableHeaderView = [[UIView alloc] initWithFrame: CGRectMake(0.0, 0.0, 320.0, 250.0)];
tableHeaderView.backgroundColor = [UIColor clearColor];
self.tableView.tableHeaderView = tableHeaderView;
Run Code Online (Sandbox Code Playgroud)

我已经尝试为tableView设置背景颜色,但这会使整个UITableView不透明(包括tableHeaderView),删除顶部的"窗口".

关于如何在设置UITableView的主体不透明时保持透明tableHeaderView的任何想法?

谢谢!

And*_*oss 6

几天后,我才弄清楚了.解决方案的前提是将子视图添加到表的backgroundView中,并在滚动时更改子视图的帧.

viewDidLoad中的相关代码:

...
// Create the UIView that will become the tableView backgroundView
UIView *tableViewBackground = [[UIView alloc] initWithFrame:self.tableView.frame];
tableViewBackground.backgroundColor = [UIColor clearColor];

// Create the opaque backgroundView and set the frame so that it starts below the headerView
partialBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 250, 320.0, self.view.frame.size.height)];
partialBackgroundView.backgroundColor = [UIColor redColor];

// Add the partial background to the main background view and apply it to the tableView
[tableViewBackground addSubview:solidTableBodyBackgroundView];
self.tableView.backgroundView = tableViewBackground;
...
Run Code Online (Sandbox Code Playgroud)

然后在滚动时,您可以更新scrollViewDidScroll中的"可见窗口":

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat scrollOffset = scrollView.contentOffset.y;
    partialBackgroundView.frame = CGRectMake(0, 250 - scrollOffset, 320, self.view.frame.size.height);
    // Other parallax code for scrolling
}
Run Code Online (Sandbox Code Playgroud)

可能有更好的方法,但我发现这很简单,效果很好.


mat*_*sed 6

为多个部分执行接受的答案的更简单方法

// Set the view for each cell with a clear color
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, SectionHeaderHeight)]; //
    view.backgroundColor = [UIColor clearColor];
    return view;
}

// Set the height of your desired header
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
Run Code Online (Sandbox Code Playgroud)