iOS - 模仿系统默认的 tableView header

4

我希望能够通过编程模仿这个头部的确切外观:enter image description here

到目前为止,我最好的尝试是:

UILabel* header = [[UILabel alloc] init] ;
header.backgroundColor = [UIColor clearColor];
header.textAlignment = NSTextAlignmentCenter;
header.textColor = [[UIColor alloc] initWithRed:86 green:92 blue:112 alpha:0.1];
header.shadowColor = [UIColor darkGrayColor];
header.shadowOffset = CGSizeMake(1,0);
header.font = [UIFont boldSystemFontOfSize:18];

但是它看起来像这样:在此输入图片描述

有人能帮我详细说明如何做吗?

提前感谢!

3个回答

3
有一位挪威人以前写过一篇关于此问题的博客文章:http://www.gersh.no/posts/view/default_styling_of_sections_headers_in_uitableview_grouped。如上图所示,所有代码版权归他所有。
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    containerView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    CGRect labelFrame = CGRectMake(20, 2, 320, 30);
    if(section == 0) {
        labelFrame.origin.y = 13;
    }
    UILabel *label = [[UILabel alloc] initWithFrame:labelFrame];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:17];
    label.shadowColor = [UIColor colorWithWhite:1.0 alpha:1];
    label.shadowOffset = CGSizeMake(0, 1);
    label.textColor = [UIColor colorWithRed:0.265 green:0.294 blue:0.367 alpha:1.000];
    label.text = [self tableView:tableView titleForHeaderInSection:section];
    [containerView addSubview:label];
    return containerView;
}

1

要么

您需要设置 header.frame = CGRectMake(10,1, 100, 18 );

或者

使用UITableView的数据源方法

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"Header"; // just pass name of your hearder
}

抱歉,我需要更具体的上下文才能进行翻译。请提供更多信息。
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
   UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
   UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 2, 100, 18)];
   label.text= [self.listOfHeader objectAtIndex:section];
   label.backgroundColor=[UIColor clearColor];
   label.textAlignment=NSTextAlignmentLeft;
   [view addSubview:label];
   return view;
}

并且添加

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

首先,10倍。我的主要目标是将文本从右到左对齐,因此我通过编程来实现这一点,因为这样做,我不能使用titleForHeaderInSection。我想手动设计 :/. - gran33

0
你可以动态/编程计算UILabel的宽度。使用以下代码:
CGSize maximumLabelSize = CGSizeMake(296,9999);
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
                        constrainedToSize:maximumLabelSize 
                        lineBreakMode:yourLabel.lineBreakMode]; 

然后将宽度增加10像素。设置您的UILabel的框架。并且,按照以下方式设置:

header.frame = CGRectMake(0.0,5.0,expectedLabelSize.width + 10.0,expectedLabelSize.height);
header.textAlignment = NSTextAlignmentRight;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接