1

我想垂直和水平居中 HeaderSection 内部的图像和图像内部的标签。但我对如何做到这一点没有明确的想法。我的代码是:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIImage *image = [UIImage imageNamed:@"bg_title_category"];
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)] autorelease];
    UILabel *sectionTitle = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)] autorelease];

    UIImageView *sectionHeaderBG;
    sectionTitle.text = @"Trial"; //[[tableDataSource objectAtIndex: section] objectForKey: @"Title"];
    sectionTitle.textAlignment = NSTextAlignmentCenter;
    sectionTitle.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];
    sectionTitle.textColor = [UIColor whiteColor];
    sectionTitle.shadowColor = [UIColor colorWithWhite:0 alpha:0.4];
    sectionTitle.shadowOffset = CGSizeMake(1, 1);
    sectionTitle.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    sectionHeaderBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, _tableView.frame.size.width/2, image.size.height)];
    sectionHeaderBG.image = [UIImage imageNamed:@"bg_title_category"];
     [headerView addSubview:sectionHeaderBG];
                [headerView addSubview:sectionTitle];
                return headerView;
}

但是这段代码没有任何中心...提前致谢!

4

1 回答 1

2

问题是您headerView使用原点 (0,0) 创建并且它的大小与您的图像相同;然后您将所有视图添加到headerView. 当表格视图添加此标题视图时,它不会居中,而是放置在 (0,0) 处。

我建议你做的是headerView用相同的原点(0,0)创建,但你的宽度tableView和高度取决于你。现在让我们假设高度与您的图像相同,加上顶部和底部的 10px 只是为了给它一些边距。然后你可以在里面添加你的UIImageViewand并将它们相对于它居中。它会是这样的:UILabelheaderView

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIImage *image = [UIImage imageNamed:@"bg_title_category"];

    // Create your headerView with the same width as the tableView and a little taller than the image
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0, tableView.bounds.size.width, image.size.height + 20)]; //10px top and 10px bottom. Just for illustration purposes.

    // Create the image view 
    UIImageView *sectionHeaderBG = [[UIImageView alloc] initWithImage:image];

    // Now center it and add it to headerView
    sectionHeaderBG.center = CGPointMake(headerView.bounds.size.width/2, headerView.bounds.size.height/2);
    [headerView addSubview: [sectionHeaderBG autorelease]];

    // Now it's turn of the label. Again I suggest using the tableView's width
    UILabel *sectionTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)];

    // Now center it. You could even do this when creating it's frame
    sectionTitle.center = CGPointMake(headerView.bounds.size.width/2, headerView.bounds.size.height/2);
    // do the rest of the configuration for your label...
    // and add it to headerView
    [headerView addSubview: [sectionTitle autorelease]];

    return [headerView autorelease];
}

希望这可以帮助!

于 2013-06-25T22:59:54.070 回答