如何:将子视图约束到安全区域对象

How to: Constrain subview to safeArea Obj-c

如何为 iPhone X 及更高版本更新此约束代码?这段代码不支持新的视图大小,我觉得它可以稍微改变一下以适应新的规范。是否应该在包含 addConstraint 的函数中进行更新?

@implementation UIView (JSQMessages)


- (void)jsq_pinSubview:(UIView *)subview toEdge:(NSLayoutAttribute)attribute
{


    [self addConstraint:[NSLayoutConstraint constraintWithItem:self
                                                     attribute:attribute
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:subview
                                                     attribute:attribute
                                                    multiplier:1.0f
                                                      constant:0.0f]];

}

- (void)jsq_pinAllEdgesOfSubview:(UIView *)subview
{


    [self jsq_pinSubview:subview toEdge:NSLayoutAttributeBottom];
    [self jsq_pinSubview:subview toEdge:NSLayoutAttributeTop];
    [self jsq_pinSubview:subview toEdge:NSLayoutAttributeLeading];
    [self jsq_pinSubview:subview toEdge:NSLayoutAttributeTrailing];
}

@end

这是我用于类似事情的代码。调整口味。

+ ( void ) embed:( UIView * ) child
        into:( UIView * ) parent
{
    [parent addSubview:child];

    [child.topAnchor    constraintEqualToAnchor:parent.topAnchor].active    = YES;
    [child.rightAnchor  constraintEqualToAnchor:parent.rightAnchor].active  = YES;
    [child.leftAnchor   constraintEqualToAnchor:parent.leftAnchor].active   = YES;
    [child.bottomAnchor constraintEqualToAnchor:parent.bottomAnchor].active = YES;
}

技巧 1:开始使用现代语法...

提示 2:不要使用 "constraint helpers",除非它能真正改善您的代码和工作流程。

提示 3:这是符合安全区域的方法:

- (void)jsq_pinAllEdgesOfSubview:(UIView *)subview
{
    UILayoutGuide *g = [self safeAreaLayoutGuide];
    [NSLayoutConstraint activateConstraints:@[
        [subview.topAnchor constraintEqualToAnchor:g.topAnchor],
        [subview.leadingAnchor constraintEqualToAnchor:g.leadingAnchor],
        [subview.bottomAnchor constraintEqualToAnchor:g.bottomAnchor],
        [subview.trailingAnchor constraintEqualToAnchor:g.trailingAnchor],
    ]];
}

谢谢大家的回答,我最终为委托创建了一个扩展并以这种方式处理了约束。这对将来使用已弃用的 JSQMessages 包的任何人都有帮助!再次感谢您的帮助。

extension JSQMessagesInputToolbar {
override open func didMoveToWindow() {
    super.didMoveToWindow()
    if #available(iOS 11.0, *), let window = self.window {
        let anchor = window.safeAreaLayoutGuide.bottomAnchor
        bottomAnchor.constraint(lessThanOrEqualToSystemSpacingBelow: anchor, multiplier: 0.3).isActive = true
        }
    }
}