gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:54:59 40 4
gpt4 key购买 nike

这让我很郁闷。我注意到有很多关于此的问题,但我似乎无法让它发挥作用。我试过 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)];

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

相反,使用约束。将标签的垂直中心限制为单元格的垂直中心,为其提供固定的宽度和固定的左边缘,并允许单元格随着其内容和(因此)其字体大小的变化而更改其自身的高度。

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

关于ios - 调整文本大小以适合宽度(1 行标签)后,如何在 UILabel 中垂直和水平居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30968464/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com