调整文本大小以适合宽度(1 行标签)后,如何在 UILabel 中垂直和水平居中?

How can I centre both vertically and horizontally in a UILabel after resizing the text to fit width (1 line label)?

这真让我沮丧。我注意到有很多关于此的问题,但我似乎无法让它发挥作用。我试过 UILabel。我已经尝试过 UITextField(它在一定程度上起作用,但如果文本太多,则某些文本不会一直调整大小)。我试过将标签模拟为 UIButton。我得不到任何东西来产生我想要的效果。我已将 UILabel 的背景颜色设置为红色,以便了解其位置。请记住,我希望 UILabel 的框架保持这个大小和位置。如果使用 UITextField 或 UIButton 更容易(也许我没有以正确的方式做到这一点),我不反对使用它们作为解决方案。

正如您从上图中看到的那样,在我的红色 UILabel 中,文本正在调整以正确适应宽度并且水平居中,但是它也没有垂直居中(我想要的)。这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if(cell == nil)
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    else
        [[cell.contentView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];


    UILabel *numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 60, 40)];
    numberLabel.font = [UIFont boldSystemFontOfSize:30];
    numberLabel.adjustsFontSizeToFitWidth = true;
    numberLabel.textAlignment = NSTextAlignmentCenter;
    [numberLabel setBackgroundColor:[UIColor redColor]];


    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, self.tableView.frame.size.width-numberLabel.frame.size.width-55, 40)];
    nameLabel.font = [UIFont boldSystemFontOfSize:20];
    nameLabel.adjustsFontSizeToFitWidth = true;
    nameLabel.textAlignment = NSTextAlignmentCenter;
    [nameLabel setBackgroundColor:[UIColor yellowColor]];


    if(indexPath.section == 0) // Weekday
    {
        numberLabel.text = weekdayBusesNumbers[indexPath.row];
        nameLabel.text = weekdayBusesNames[indexPath.row];
    }

    else if(indexPath.section == 1) // Saturday
    {
        numberLabel.text = saturdayBusesNumbers[indexPath.row];
        nameLabel.text = saturdayBusesNames[indexPath.row];
    }

    else if(indexPath.section == 2) // Sunday
    {
        numberLabel.text = sundayBusesNumbers[indexPath.row];
        nameLabel.text = sundayBusesNames[indexPath.row];
    }


    [cell.contentView addSubview:numberLabel];
    [cell.contentView addSubview:nameLabel];


    return cell;
}

您正在将标签设置为单行标签(默认情况下)并将其高度设置为固定高度,从而固定其位置:

UILabel *numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, 60, 40)];

因此,无论字体大小如何,您都会为所有标签获得一个不变的基线位置。因此,无论字母有多高,每个字母都从 相同的基线 上升。

而是使用约束。将标签的垂直中心约束到单元格的垂直中心,给它一个固定的宽度和一个固定的左边缘,并允许单元格随着它的内容和(因此)它的字体大小的变化而改变它自己的高度。

您可以在标签后面放一个红色矩形,这样用户就无法区分标签和红色矩形。因此,文本将在红色矩形中垂直居中显示,这就是您想要的效果。