中心 UILabel 子视图

Posted

技术标签:

【中文标题】中心 UILabel 子视图【英文标题】:Center UILabel Subview 【发布时间】:2015-05-08 15:33:41 【问题描述】:

我有一个 UIImageView 作为我的表格视图的背景视图。当表格没有数据时,我将添加一个 UILabel 作为图像视图的子视图。我无法让标签居中。标签总是偏右。

UIImageView *backgroundImageView = [[UIImageView alloc]initWithFrame:self.tableView.frame];
    backgroundImageView.image = [UIImage imageNamed:@"background"];
    backgroundImageView.center = self.tableView.center;

    self.noLocationsLabel = [[UILabel alloc]initWithFrame:backgroundImageView.frame];
    self.noLocationsLabel.center = backgroundImageView.center;
    self.noLocationsLabel.text = @"No saved locations";
    self.noLocationsLabel.textAlignment = NSTextAlignmentCenter;
    self.noLocationsLabel.textColor = [UIColor blackColor];
    self.noLocationsLabel.font = [UIFont fontWithName:@"Chalkboard SE" size:24.0];

self.tableView.backgroundView = backgroundImageView;

if (self.locationsArray.count == 0) 
        self.navigationItem.rightBarButtonItem.enabled = NO;

        [self.tableView.backgroundView addSubview:self.noLocationsLabel];
        self.tableView.userInteractionEnabled = NO;
    

【问题讨论】:

为什么要将图像视图框架给 uilabel 框架? 【参考方案1】:

如果您的图像框架是 50,50,50,50,那么您的标签也将是 50,50,50,50,但由于它是图像视图的子视图,它永远不会位于中心。同样的概念适用于center。中心仅针对视图超级视图。

为了使其居中,您可以将框架设置为:

CGRect rect = CGRectMake(0,0,backgroundImageView.frame.size.width,backgroundImageView.frame.size.height);

self.noLocationsLabel = [[UILabel alloc]initWithFrame: rect];

或者甚至:

self.noLocationsLabel = [[UILabel alloc]initWithFrame: backgroundImageView.bounds];

编辑:

您可以在子视图上使用center。但是你必须设置正确的中心。

self.noLocationsLabel.center = CGPointMake(CGRectGetMidX(backgroundImageView.bounds),CGRectGetMidY(backgroundImageView.bounds));

Difference between frame and bounds

【讨论】:

所以您是说中心仅适用于父视图? @弗兰基 我尝试像您在编辑中所做的那样设置标签的中心,但这并不能解决问题。 在将noLocationsLabelbackgroundImageView 添加为子视图后,您能否记录其框架? self.tableView: 0, 0, 600, 600,背景框架:0, 0, 600, 600,标签框架:0, 0, 600, 600

以上是关于中心 UILabel 子视图的主要内容,如果未能解决你的问题,请参考以下文章

将 UILabel 放在集合视图的中心?

为啥 UIStackView 不堆叠 UILabel 安排的子视图?

UILabel 未在 iOS8 中显示子视图

没有子视图时更新uilabel的宽度

如何设置 UIView 高度等于两个子视图 UILabel 的最大值?

如何设置UIView高度等于两个子视图UILabel的最大值?