uitableview标题背景直到滚动才显示

时间:2013-05-19 09:24:44

标签: ios uitableview

我使用以下代码设置uitableview部分的标题视图。问题是,在滚动tableview之前,背景颜色(mainLightColor_2)不会显示。如何在加载时显示背景颜色?

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 24)];
  headerView.backgroundColor = [Utility mainLightColor_2]; //mainLightColor is a blue color

  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 2, 200, 20)];
  label.backgroundColor = [UIColor clearColor];
  label.textColor = [Utility mainDarkColor];
  label.text = @"Past Activities";
  [headerView addSubview:label];

  return headerView;
}

滚动前: Before scroll

滚动后: After scroll

2 个答案:

答案 0 :(得分:1)

您还应该实施- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section方法。

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

答案 1 :(得分:1)

所以我找到了解决方法。但是,我仍然不明白为什么设置headerView的背景颜色不起作用。

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
  UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 24)];

  UIView *headerViewBackground = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 24)];
  headerViewBackground.backgroundColor = [Utility mainLightColor_2];
  [headerView addSubview:headerViewBackground];

  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5, 2, 200, 20)];
  label.backgroundColor = [UIColor clearColor];
  label.textColor = [Utility mainDarkColor];
  label.text = @"Past Activities";
  [headerView addSubview:label];

  return headerView;
}