如何将titleForHeaderInSection的文本设置为AlignmentCenter

时间:2013-04-01 09:16:22

标签: iphone ios

我使用以下代码在组tableview标题标题中设置标题,但默认文本是AlignmentLeft,如何对齐AlignmentCenter?

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if(section==0){
        return NSLocalizedString(@"more_titlehead_one", nil);
    }else if (section==1){
        return NSLocalizedString(@"more_titlehead_two", nil);
    }else{
        return NSLocalizedString(@"more_titlehead_three", nil);
    }


}

3 个答案:

答案 0 :(得分:11)

试试这个,

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
     UILabel * sectionHeader = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
     sectionHeader.backgroundColor = [UIColor clearColor];
     sectionHeader.textAlignment = UITextAlignmentCenter;
     sectionHeader.font = [UIFont boldSystemFontOfSize:10];
     sectionHeader.textColor = [UIColor whiteColor];

     switch(section) {
        case 0:sectionHeader.text = @"TITLE ONE"; break;
        case 1:sectionHeader.text = @"TITLE TWO"; break;
        default:sectionHeader.text = @"TITLE OTHER"; break;
     }  
   return sectionHeader;
}

为标题设置一些默认高度,

- (CGFloat)tableView:(UITableView *)tableViewheightForHeaderInSection:(NSInteger)section {
     switch(section) {
        case 0:
        case 1:
        default:return 20;
     }  
}

答案 1 :(得分:4)

使用以下方法为每个部分中的标题设置UIView项:

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerVw = [[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 30)] autorelease];
    headerVw.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"title_bg.png"]]; // set color of header

    UILabel *itemlbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 320, 20)];

    if(section==0){
        itemlbl.text = NSLocalizedString(@"more_titlehead_one", nil);
    }else if (section==1){
        itemlbl.text = NSLocalizedString(@"more_titlehead_two", nil);
    }else{
        itemlbl.text = NSLocalizedString(@"more_titlehead_three", nil);
    }
    itemlbl.textAlignment = UITextAlignmentCenter;
    itemlbl.backgroundColor = [UIColor clearColor];
    itemlbl.textColor = [UIColor whiteColor];
    itemlbl.font = [UIFont boldSystemFontOfSize:14];
    [headerVw addSubview:itemlbl];
    [titlelbl release];
    return headerVw;
}

祝你好运

答案 2 :(得分:2)

使用UILabel非常简单,其对齐中心。在viewForHeaderInSection

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UILabel *lbl = [[[UILabel alloc] init] autorelease];
    lbl.textAlignment = UITextAlignmentCenter;
    lbl.backgroundColor=[UIColor clearColor];
    lbl.text = @"Header Title";
    return lbl;
}