向下滚动后更改节标题视图

时间:2013-12-14 12:38:23

标签: ios objective-c cocoa-touch ios7

我希望在用户向下滚动时修改节标题视图,类似于音乐应用中的此类视图 (Notics视图背景颜色如何变化并获得底部边框)

screen shots http://f.cl.ly/items/3q123Z3N0k4117331Q0Q/Untitled-1.png

是否有一种很好的方法可以跟踪视图何时位于该部分的顶部或滚动位置?

更新

到目前为止我唯一的解决方案是保留所有节头视图的数组并更改scrollViewDidScroll:delegate方法中的第一个可见节的视图(使用tableView.indexPathsForVisibleRows数组获取第一个可见节索引)

如果有人能想出更简单的方法,那就太棒了!

2 个答案:

答案 0 :(得分:2)

您可以在scrollViewDidScroll方法中修改节标题视图的颜色(以及您想要的任何其他内容)。此示例在用户向下滚动时使浮动标题视图的颜色变暗,并将该颜色的白色值保持在0.9和0.6之间。如果向下滚动超过5个点,它也会在标题视图中取消隐藏底部边框线。

RDHeaderView的.m文件:

- (id)init{
    self = [super init];
    if (self) {
        UIView *line = [[UIView alloc] init];
        [line setTranslatesAutoresizingMaskIntoConstraints:NO];
        line.backgroundColor = [UIColor darkGrayColor];
        [self addSubview:line];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[line]|" options:0 metrics:nil views:@{@"line":line}]];
        [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[line]|" options:0 metrics:nil views:@{@"line":line}]];
        [line addConstraint:[NSLayoutConstraint constraintWithItem:line attribute:NSLayoutAttributeHeight relatedBy:0 toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:1]];
        self.bottomLine = line;
        self.bottomLine.hidden = YES;
    }
    return self;
}

表视图控制器中的相关方法:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    RDHeaderView *header = [[RDHeaderView alloc] init];
    header.contentView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    return header;
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSInteger topSection = [[self.tableView indexPathsForVisibleRows].firstObject section];
    NSInteger sectionYOffset = [self.tableView rectForHeaderInSection:topSection].origin.y;
    RDHeaderView *pinnedHeader = (RDHeaderView *)[self.tableView headerViewForSection:topSection];
    pinnedHeader.bottomLine.hidden = ((scrollView.contentOffset.y - sectionYOffset) > 5)? NO: YES;
    CGFloat colorOffset = fmaxf(0.6, 0.9 - (scrollView.contentOffset.y - sectionYOffset)/1000.0);
    if (colorOffset > 0.9) colorOffset = 0.9;
    pinnedHeader.contentView.backgroundColor = [UIColor colorWithWhite:colorOffset alpha:1];
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 80;
}

答案 1 :(得分:0)

也许存在一个更简单的解决方案,但这是实现您想要的一种方式:

  • 删除tableHeader,并将其作为单独的子视图添加到viewControllers视图中(NB不要使用uitableviewController,因为viewController将tableview作为其视图,你不希望这样)

  • 向下移动tableView,使其适合前面的tableheader视图

  • 计算并设置tableView的contentOffset(它是一个UIScrollView),这样单元格似乎不会跳转到新位置。

此外,你可以尝试返回一个sectionHeaderView(它与tableView一起向下滚动,但不能向上滚动,例如在你的联系人列表中看到它是如何工作的)。使用该视图作为单元格或节标题。