ios - 如何为具有不透明主体的 UITableView header 设置清晰的背景

标签 ios nstableheaderview uitableview

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

我正在使用透明的 tableHeaderView 来实现视差效果。 tableView 后面的对象比清晰的 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;

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

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

谢谢!

最佳答案

几天后我就弄明白了。解决方案的前提是在表格的 backgroundView 中添加一个 subview 并在滚动时更改 subview 的 frame。

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;
...

然后当你滚动时,你可以更新 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
}

可能有更好的方法来做到这一点,但我发现这很简单而且效果很好。

关于ios - 如何为具有不透明主体的 UITableView header 设置清晰的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20154274/

相关文章:

ios - 如何禁用 UIScrollView 中的水平滚动?

swift - 快速访问表格 View 中的每个标题和控件

cocoa - 如何在基于 View 的 NSTableView 中设置 NSTableColumn 的列名?

ios - 具有自动布局的 UITableViewCell 中的动态大小的 UIWebView - 违反约束

javascript - 检测 UIWebView 文本选择中的文本选择变化

iphone - 因启动时崩溃而被拒绝

ios - swift:集合中的图像

IOS swift tableview获取一个部分的headerview

ios - 与 UITableView 外部的其他按钮相比,TableHeaderView 中的自定义 UIButton 响应速度不快

ios - 如何只允许一个单元格可点击