UITableViewCell中的中心标签

use*_*468 4 objective-c uitableview ios

我正在尝试以编程方式将自定义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;
}
Run Code Online (Sandbox Code Playgroud)

这是一张它看起来如何的图片.你可以看到它没有居中.我怎么能把它集中起来?

在此输入图像描述

san*_*ony 6

cell.homeTeamLabel.textAlignment = UITextAlignmentCenter;
Run Code Online (Sandbox Code Playgroud)

我的错.这是星期天早上,我需要更多咖啡!

iOS6及以上版本使用

cell.homeTeamLabel.textAlignment = NSTextAlignmentCenter;
Run Code Online (Sandbox Code Playgroud)

  • UITextAlignmentCenter已弃用 (2认同)

And*_*riy 5

UILabel垂直居中对齐文本。您需要做的所有事情就是确保标签占据整个单元格并设置textAlignmentNSTextAlignmentCenter

顺便说一句,您不必定义自己的标签。只需使用UITableViewCell提供的一种即可(cell.textLabel针对您的情况)。