【问题标题】:UITableView & Sections - to detect if a section header is stays on topUITableView & Sections - 检测节标题是否保持在顶部
【发布时间】:2014-05-17 03:48:46
【问题描述】:

我需要这个,因为我需要更改部分的背景颜色。例如,如果部分位于顶部,则为蓝绿色,否则。

我尝试了很多事情,但最后我还是坚持了自己的想法。

【问题讨论】:

  • 你是什么意思“捕捉到顶部”?
  • 我的意思是当一个部分保持在顶部时。
  • 整个部分,还是一些标题?请更具体。并且看到您提到的至少一种方法会很有帮助。
  • 只有标题而不是整个部分。
  • 你试过的代码在哪里?

标签: objective-c uitableview


【解决方案1】:

试试这个

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.backgroundColor = section == 0 ? [UIColor blueColor] : [UIColor greenColor];

    // Another way to set the background color
    // Note: does not preserve gradient effect of original header
    // UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    // header.contentView.backgroundColor = [UIColor blackColor];
}

考虑到顶部意味着第一部分。

编辑

如果您想根据滚动来更改颜色并确定哪个部分在顶部,哪个部分不在,那么您必须实现 UIScrollViewDelegate 以便您可以处理滚动委托。你可以试试这样的

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    NSIndexPath *firstVisibleIndexPath = [[self.tableView indexPathsForVisibleRows] objectAtIndex:0];
    NSLog(@"first visible cell's section: %i, row: %i", firstVisibleIndexPath.section, firstVisibleIndexPath.row);
}

参考:UIScrollViewDelegate implementationDetecting top cell in TableView

【讨论】:

  • 不是真的,我的意思是一个部分在顶部。我知道我的问题不够清楚。但我会尝试你的解决方案。听起来很好。有人认为:'view.backgroundColor' 已被弃用,使用'contentView.backgroundColor' 说是 Xcode。
  • 这是不正确的。第 0 部分可能显示也可能不显示,具体取决于内容长度和部分数量。
  • 您的解决方案是干净的 :) 我只给出了要遵循的路径,但您准确地回答了它(Y)
  • 它的工作并不正确,但我会尝试修复它。
  • 那太慢了,因为在每个滚动点之后,您将查询表格视图以获取显示的单元格的索引路径。 willDisplayHeaderView 是正确的位置。
【解决方案2】:

试试这个:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    NSArray* visibleCellIndexPaths = [tableView indexPathsForVisibleRows];

    //Set all header views to have a blue background color.
    [view setBackgroundColor:[UIColor blueColor]];

    if(visibleCellIndexPaths.count > 0)
    {
        //Set the topmost visible section header view to have green background color.
        [[tableView headerViewForSection:[visibleCellIndexPaths[0] section]] setBackgroundColor:[UIColor greenColor]];
    }
}

【讨论】:

    【解决方案3】:

    只需检查您要查找的节标题的框架是否已移到顶部。

    【讨论】:

      【解决方案4】:

      @faisal Ali 答案的 Swift 版本

      func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
          view.backgroundColor = section == 0 ? UIColor.white : UIColor.clear
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-15
        • 1970-01-01
        • 2023-03-07
        • 2020-08-08
        • 1970-01-01
        • 2011-05-15
        相关资源
        最近更新 更多