UITableViewCell中的中心标签

时间:2014-02-09 15:50:46

标签: ios objective-c uitableview

我正在尝试以编程方式将自定义UILabel中心放入UITableViewCell。问题是它似乎没有中心。我正在使用此代码:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    chatCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) cell = [[chatCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    float yPos = (CGRectGetHeight(cell.contentView.frame) - CGRectGetHeight(cell.homeTeamLabel.frame)) / 2;

    cell.homeTeamLabel = [[UILabel alloc] initWithFrame:CGRectMake(22.0, yPos, 220.0, 15.0)];
    cell.homeTeamLabel.text = [items objectAtIndex:indexPath.row];
    cell.homeTeamLabel.font = [UIFont systemFontOfSize:14.0];
    cell.homeTeamLabel.textColor = [UIColor blackColor];
    [cell.contentView addSubview:cell.homeTeamLabel];


    return cell;
}

这是一张它看起来如何的照片。你可以看到它没有居中。我该如何居中呢?

enter image description here

2 个答案:

答案 0 :(得分:6)

cell.homeTeamLabel.textAlignment = UITextAlignmentCenter;

我的坏。这是周日早上,我需要更多咖啡!

iOS 6及更高版本使用

cell.homeTeamLabel.textAlignment = NSTextAlignmentCenter;

答案 1 :(得分:5)

UILabel中心文字垂直。您需要做的就是确保您的标签占据整个单元格并将textAlignment设置为NSTextAlignmentCenter

顺便说一下,您不必定义自己的标签。只需使用UITableViewCell为此目的提供的cell.textLabel就可以了。

相关问题