2

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

- (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);
    }


}
4

3 回答 3

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;
     }  
}
于 2013-04-01T09:22:22.813 回答
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;
}

祝你好运

于 2013-04-01T09:20:32.070 回答
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;
}
于 2013-04-01T09:20:53.340 回答