2

我正在尝试实现一个删除整个部分的控件,如果删除按钮位于标题中,它在我的应用程序中看起来最好,而不是像 UIPopoverView 这样的覆盖。


在写这个问题的过程中,我找到了答案。很简单,一旦有了起点。

4

1 回答 1

11

我从这个只有两篇文章的博客中得到了大部分代码,都是从 2010 年开始的。
然后我回到这个网站只是为了字体颜色,因为分解起来更麻烦。

三个小问题,都与标签有关。

- Font is too narrow
- Text color is too dark
- Label origin is wrong

默认字体是已知的,所以它是第一位的。

label.font = [UIFont boldSystemFontOfSize:17.0];

颜色是下一个,因为这很容易。为此使用了图像编辑器的吸管工具。

label.textColor = [UIColor colorWithRed:0.298 green:0.337 blue:0.423 alpha:1];
// Is there a difference between alpha:1 and alpha:1.000?

然后是困难的部分。一个接近的猜测,然后进行一些调整以获得完美匹配。

label.frame = CGRectMake(54, 4, headerView.frame.size.width-20, 22);

现在我们有了一个与当前 Grouped 标头完美匹配的自定义实现。

完成代码:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 40)];
    tableView.sectionHeaderHeight = headerView.frame.size.height;

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(54, 4, labelSize.width, labelSize.height)];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setFont:[UIFont boldSystemFontOfSize:17.0]];
    [label setShadowColor:[UIColor whiteColor]];
    [label setShadowOffset:CGSizeMake(0, 1)];
    [label setText:[self tableView:tableView titleForHeaderInSection:section]];
    [label setTextColor:[UIColor colorWithRed:0.298 green:0.337 blue:0.423 alpha:1.000]];
    [headerView addSubview:label];

    return headerView;
}

在自己找到正确的字体/颜色后找到了这个SO 答案。那好吧。

编辑:

对于允许有效无限量文本的标题标签:

// before label init
NSString *title = [self tableView:tableView titleForHeaderInSection:section];
NSUInteger maxWidth = headerView.frame.size.width-108;
CGSize labelSize = [title sizeWithFont:[UIFont systemFontOfSize:17.0]
                     constrainedToSize:CGSizeMake(maxWidth, CGFLOAT_MAX)];
if (labelSize.width < maxWidth) labelSize.width = maxWidth;

// after setFont:
[label setNumberOfLines:0];
于 2012-08-21T14:41:02.713 回答