Как программно центрировать UILabel в UIView? - PullRequest
0 голосов
/ 05 февраля 2020

Я прошел через эту ветку и в значительной степени перепробовал каждое предложение, но мой ярлык все равно отказывается центрироваться в view:

Как центрировать UILabel на UIView

Это самое близкое, что я получаю:

enter image description here

Моя первая мысль состояла в том, что view скрывается под tab bar, но согласно debug hierarchy view заканчивается прямо там, где начинается 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];

Ответы [ 2 ]

1 голос
/ 05 февраля 2020

Вы будете намного лучше учиться / использовать ограничения и автоматическое размещение.

Вот то, что вы пытаетесь сделать, но это будет автоматическое расположение правильно для всех различных устройств и поворотов:

_noExperiences = [UIView new];
_noExperiences.backgroundColor = [UIColor whiteColor];

UILabel *nothingToShow = [UILabel new];
nothingToShow.text = @"HELLO";
nothingToShow.textColor = [UIColor blackColor];
nothingToShow.textAlignment = NSTextAlignmentCenter;
[nothingToShow setNumberOfLines: 0];
[nothingToShow setFont:[UIFont fontWithName: @"Trebuchet MS" size: 14.0f]];

// add _noExperiences to self.view
[self.view addSubview:_noExperiences];

// add nothingToShow to _noExperiences
[_noExperiences addSubview:nothingToShow];

// we'll use auto-layout, so set to NO
_noExperiences.translatesAutoresizingMaskIntoConstraints = NO;
nothingToShow.translatesAutoresizingMaskIntoConstraints = NO;

// let's respect safe area
UILayoutGuide *g = self.view.safeAreaLayoutGuide;

[NSLayoutConstraint activateConstraints:@[

    // constrain _noExperiences view to safe area
    [_noExperiences.topAnchor constraintEqualToAnchor:g.topAnchor constant:0.0],
    [_noExperiences.bottomAnchor constraintEqualToAnchor:g.bottomAnchor constant:0.0],
    [_noExperiences.leadingAnchor constraintEqualToAnchor:g.leadingAnchor constant:0.0],
    [_noExperiences.trailingAnchor constraintEqualToAnchor:g.trailingAnchor constant:0.0],

    // constrain nothingToShow label centered in _noExperiences view
    [nothingToShow.centerXAnchor constraintEqualToAnchor:_noExperiences.centerXAnchor],
    [nothingToShow.centerYAnchor constraintEqualToAnchor:_noExperiences.centerYAnchor],

]];

РЕДАКТИРОВАТЬ

Если вы действительно необходимо поддерживать 7 пользователей, которые используют iOS версию ранее 11, вы можете попробовать это для обработки пропавшего safeAreaLayoutGuide:

// let's respect safe area for iOS 11+
// or layoutMarginsGuide for earlier
UILayoutGuide *g;
CGFloat standardSpacing = 0.0;

if (@available(iOS 11, *)) {
    // iOS 11 (or newer) ObjC code
    g = self.view.safeAreaLayoutGuide;
    [NSLayoutConstraint activateConstraints:@[
        // constrain _noExperiences view to safe area
        [_noExperiences.topAnchor constraintEqualToAnchor:g.topAnchor constant:0.0],
        [_noExperiences.bottomAnchor constraintEqualToAnchor:g.bottomAnchor constant:0.0],
        [_noExperiences.leadingAnchor constraintEqualToAnchor:g.leadingAnchor constant:0.0],
        [_noExperiences.trailingAnchor constraintEqualToAnchor:g.trailingAnchor constant:0.0],
    ]];
} else {
    // iOS 10 or older code
    standardSpacing = 8.0;
    g = self.view.layoutMarginsGuide;
    [NSLayoutConstraint activateConstraints:@[
        // constrain _noExperiences view to layout margins guide
        [_noExperiences.topAnchor constraintEqualToAnchor:g.topAnchor constant:standardSpacing],
        [_noExperiences.bottomAnchor constraintEqualToAnchor:g.bottomAnchor constant:-standardSpacing],
        [_noExperiences.leadingAnchor constraintEqualToAnchor:g.leadingAnchor constant:0.0],
        [_noExperiences.trailingAnchor constraintEqualToAnchor:g.trailingAnchor constant:0.0],
    ]];
}

[NSLayoutConstraint activateConstraints:@[

    // constrain nothingToShow label centered in _noExperiences view
    [nothingToShow.centerXAnchor constraintEqualToAnchor:_noExperiences.centerXAnchor],
    [nothingToShow.centerYAnchor constraintEqualToAnchor:_noExperiences.centerYAnchor],

]];
0 голосов
/ 05 февраля 2020

пожалуйста, попробуйте для быстрого:

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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...