【问题标题】:Problems setting view for header in a grouped table为分组表中的标题设置视图时出现问题
【发布时间】:2013-07-31 14:01:48
【问题描述】:

我正在尝试为分组表中的部分自定义标题。我为表格中的第一部分设置的视图看起来不错,但随后的部分标题看起来在顶部和底部被裁剪(在此屏幕截图中仅显示在顶部):

我一直在为frame.size.origin 尝试不同的 X 和 Y 值,但看起来还是一样。这是我的代码:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
   if (section == 1) {
          UIView *wrapper = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 70)];
          [wrapper setBackgroundColor:[UIColor clearColor]];

          UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, self.tableView.frame.size.width, 20)];
          label.text = NSLocalizedString(@"Section 2 Header", @"");
          [label setFont:[UIFont boldSystemFontOfSize:15]];
          [label setBackgroundColor:[UIColor clearColor]];

          [wrapper addSubview:label];

          return wrapper;
   }

   else
          return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
   if (section == 1)
          return 70;
   else
          return 0;
}

我对所有部分标题都做了同样的事情,只有第一个正确显示,我做错了什么?关于这个问题,是否可以动态知道 UILabel 的高度,一旦其文本和字体大小已知,或者您是否应该始终“猜测”设置其帧大小? heightForHeaderInSection: 方法中设置的标题的视图高度相同。

谢谢!

【问题讨论】:

  • 设置好标签后,拨打[label sizeToFit];。这将确保标签的框架正确地适合文本。之后您可能需要更新标签的来源。
  • 您的代码仅适用于第一部分。如果您需要所有部分,您应该在您的方法中删除if (section == 1) 或提供if (section == 2) 等。希望对您有所帮助。或者您可以致电(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { 并为页脚插入高度。
  • @user2545330 我在这里省略了其余部分的代码,因为它非常相似,我不想粘贴很长的代码 sn-p
  • @rmaddy 有没有办法在heightForHeaderInSection: 中设置headerView.frame.size.height 之类的东西,或者像我现在这样提供一个固定值?看起来heightForHeaderInSection: 方法是在viewForHeaderInSection: 方法之前调用的,但是如果您此时不知道标题中标签的高度会怎样呢?
  • @AppsDev 使用:- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section { return 30.0f; }

标签: ios css header


【解决方案1】:

此代码中除第 1 节以外的节您没有设置标题的高度,您应该删除 if(section==1) 条件并为每个节提供通用高度然后检查

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
   if (section == 1)
          return 70;
   else
          return 0;
}

谢谢, 米塔尔。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多