在UITableView中设置自定义标题视图

时间:2013-04-30 18:06:24

标签: ios uitableview custom-headers

我正在尝试向每个UITableView部分的标题添加自定义视图。我正在使用此委托方法返回所需的视图。它的工作部分是因为它导致单元格部分展开,好像那里有一个标题,但文本或UIButton实际上都没有出现。我知道正在调用此方法,因为我在方法中放置了一个NSLog来查看它是否存在。我是否犯了某种愚蠢的错误,或者这不是正确的做法?

 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {
        UIView* customView = [[UIView alloc]initWithFrame:CGRectMake(0.0, 0.0, tableView.bounds.size.width, 44.0)];
        customView.backgroundColor = [UIColor clearColor];

        UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 44.0)];
        headerLabel.textColor = [UIColor darkGrayColor];
        headerLabel.font = [UIFont boldSystemFontOfSize:16];


        UIButton *headerButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        // add button to right corner of section

        return customView;
        switch (section) {
            case 0:
                headerLabel.text = @"Team Name";
                break;
            case 1:
                headerLabel.text = @"Captain";
                break;
            case 2:
                headerLabel.text = @"Wicket Keeper";
                break;
            case 3:
                headerLabel.text = @"Batting Order";
                headerButton.center = CGPointMake( 160.0, 22.0);
                headerButton.backgroundColor = [UIColor blueColor];
                headerButton.tag = section;
                [headerButton   addTarget:self action:@selector(enableCellReordering:) forControlEvents:UIControlEventTouchUpInside];
                [customView addSubview:headerButton];
                break;
            default:
                break;
        }

        [customView addSubview:headerLabel];
        return customView;
    }

4 个答案:

答案 0 :(得分:2)

return customView;声明之前找到它switch

答案 1 :(得分:1)

return customview两次,一次切换语句后一次切换语句两次只需删除return customView;之前的switch (section)

答案 2 :(得分:0)

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)];
    /* Create custom view to display section header... */
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)];
    [label setFont:[UIFont boldSystemFontOfSize:12]];
     NSString *string =[list objectAtIndex:section];
    /* Section header is in 0th index... */
    [label setText:string];
    [view addSubview:label];
    [view setBackgroundColor:[UIColor colorWithRed:166/255.0 green:177/255.0 blue:186/255.0 alpha:1.0]]; //your background color...
    return view;
}

答案 3 :(得分:0)

自定义标头origin.x和origin.y怎么样? 当我将它们设置为非零时,它仍然位于ledt边缘旁边。