我如何以编程方式将UILabel居中于UIView?

问题描述 投票:0回答:1

我经历了这个话题,几乎对每个建议都进行了尝试,但是我的标签仍然拒绝在view中居中:

How to center a UILabel on UIView

这是我得到的最接近的:

enter image description here

[我首先想到的是view隐藏在tab bar下,但根据debug hierarchyview恰好在tab bar开始的位置结束。

代码看起来像这样:

    _noExperiences = [[UIView alloc] initWithFrame:self.view.frame];
    _noExperiences.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_noExperiences];

    UILabel *nothingToShow = [[UILabel alloc] initWithFrame:CGRectMake(_noExperiences.center.x, _noExperiences.center.y, 200, 20)];
    nothingToShow.text = @"HELLO";
    nothingToShow.textColor = [UIColor blackColor];
    nothingToShow.textAlignment = NSTextAlignmentCenter;
    [nothingToShow setNumberOfLines: 0];
    [nothingToShow sizeToFit];

    [nothingToShow setCenter: CGPointMake(_noExperiences.center.x, _noExperiences.center.y)];
    [nothingToShow setFont:[UIFont fontWithName: @"Trebuchet MS" size: 14.0f]];

    [_noExperiences addSubview:nothingToShow];
ios objective-c uiview uilabel centering
1个回答
0
投票
请尝试快速操作:

let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21)) label.center = view.center label.textAlignment = .center label.text = "label" self.view.addSubview(label)

© www.soinside.com 2019 - 2024. All rights reserved.