Использование максимального экрана в альбомной ориентации на iPhone X

В настоящее время я настраиваю ограничения макета веб-представления следующим образом:

UIView *theView = self.view;
UILayoutGuide *theGuide = theView.safeAreaLayoutGuide;

inWebView.translatesAutoresizingMaskIntoConstraints = NO;
[theView.topAnchor constraintEqualToAnchor:inWebView.topAnchor].active = YES;
[theGuide.leadingAnchor constraintEqualToAnchor:inWebView.leadingAnchor].active = YES;
[theGuide.trailingAnchor constraintEqualToAnchor:inWebView.trailingAnchor].active = YES;
[theView.bottomAnchor constraintEqualToAnchor:inWebView.bottomAnchor].active = YES;

Что приводит к левому и правому полям, когда вид отображается на iPhone X в ландшафтном режиме. Веб-представление центрируется по горизонтали в представлении. Это показано как (1) в следующем эскизе  введите описание изображения здесь , где веб-представление отображается в виде зеленой области.

Но я хочу использовать максимальную ширину представления, при котором веб-представление простирается до правого (2) или левого края (3). Для этого потребуется руководство по динамическому макету для начала и конца.

Как я могу этого добиться?


person clemens    schedule 24.01.2018    source источник


Ответы (1)


Я нашел решение, добавив дополнительные ограничения:

@property (nonatomic, strong) NSLayoutConstraint *leftFullConstraint;
@property (nonatomic, strong) NSLayoutConstraint *rightFullConstraint;

и инициализируем ограничения вида:

UIView *theView = self.view;
UILayoutGuide *theGuide = theView.safeAreaLayoutGuide;
NSLayoutConstraint *theConstraint;

inWebView.translatesAutoresizingMaskIntoConstraints = NO;
[theView.topAnchor constraintEqualToAnchor:inWebView.topAnchor].active = YES;
theConstraint = [theGuide.leadingAnchor constraintEqualToAnchor:inWebView.leadingAnchor];
theConstraint.priority = UILayoutPriorityDefaultHigh;
theConstraint.active = YES;
theConstraint = [theGuide.trailingAnchor constraintEqualToAnchor:inWebView.trailingAnchor];
theConstraint.priority = UILayoutPriorityDefaultHigh;
theConstraint.active = YES;
[theView.bottomAnchor constraintEqualToAnchor:inWebView.bottomAnchor].active = YES;

self.leftFullConstraint = [theView.leftAnchor constraintEqualToAnchor:inWebView.leftAnchor];
self.rightFullConstraint = [theView.rightAnchor constraintEqualToAnchor:inWebView.rightAnchor];

Примечание: новые ограничения, использующие левое и правое, вместо начала и конца, потому что направление письма не имеет значения! Они имеют более высокий приоритет, чем ограничения в руководстве по макету области сохранения. Поэтому, когда приложение активирует его, они отменят ограничения для безопасной области.

Наконец, ограничения обновляются при изменении коллекции признаков:

- (void)updateConstraints {
    UIDeviceOrientation theOrientation = [[UIDevice currentDevice] orientation];

    switch (theOrientation) {
        case UIDeviceOrientationLandscapeLeft:
            self.leftFullConstraint.active = NO;
            self.rightFullConstraint.active = YES;
            break;
        case UIDeviceOrientationLandscapeRight:
            self.leftFullConstraint.active = YES;
            self.rightFullConstraint.active = NO;
            break;
        default:
            self.leftFullConstraint.active = NO;
            self.rightFullConstraint.active = NO;
    }
}

- (void)traitCollectionDidChange:(UITraitCollection *)inPreviousTraitCollection {
    [super traitCollectionDidChange:inPreviousTraitCollection];
    [self updateConstraints];
}

То же самое для Swift 4. Определение свойств:

var leftFullConstraint: NSLayoutConstraint?
var rightFullConstraint: NSLayoutConstraint?

Инициализация ограничений:

if let theView = self.view {
    let theGuide = theView.safeAreaLayoutGuide
    var theConstraint: NSLayoutConstraint!

    inWebView.translatesAutoresizingMaskIntoConstraints = false
    theView.topAnchor.constraint(equalTo: inWebView.topAnchor).isActive = true
    theConstraint = theGuide.leadingAnchor.constraint(equalTo: inWebView.leadingAnchor)
    theConstraint.priority = UILayoutPriorityDefaultHigh
    theConstraint.isActive = true
    theConstraint = theGuide.trailingAnchor.constraint(equalTo:inWebView.trailingAnchor)
    theConstraint.priority = UILayoutPriorityDefaultHigh
    theConstraint.isActive = true
    theView.bottomAnchor.constraint(equalTo: inWebView.bottomAnchor).isActive = true

    self.leftFullConstraint = theView.leftAnchor.constraint(equalTo: inWebView.leftAnchor)
    self.rightFullConstraint = theView.rightAnchor.constraint(equalTo: inWebView.rightAnchor)
}

и обновляя их:

func updateConstraints() {
    if let leftFullConstraint = self.leftFullConstraint, 
       let rightFullConstraint = self.rightFullConstraint {
        let theOrientation = UIDevice.current.orientation

        switch(theOrientation) {
        case .landscapeLeft:
            leftFullConstraint.isActive = false
            rightFullConstraint.isActive = true
            break;
        case .landscapeRight:
            leftFullConstraint.isActive = true
            rightFullConstraint.isActive = false
            break
        default:
            leftFullConstraint.isActive = false
            rightFullConstraint.isActive = false
        }
    }
}

override func traitCollectionDidChange(_ inPreviousTraitCollection: UITraitCollection?) {
    super.traitCollectionDidChange(inPreviousTraitCollection)
    updateConstraints()
}
person clemens    schedule 30.01.2018