如何:将子视图约束到安全区域 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:不要使用"约束帮助程序",除非它确实会改善您的代码和工作流程。

提示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
}
}
}

最新更新