如何设置相对于超级视图高度的topAnchor约束

How to set topAnchor constraint relative to the superview height

我有两个观点:toastViewviewtoastViewview 的子视图。 我想将 toastView 在 y 轴上定位 view 高度的 80%。 我如何在代码中使用常量来做到这一点?

我假设有这样一种方法:

[toastView.topAnchor constraintEqualToAnchor:view.heightAnchor multiplier:0.8].active = YES;

但我不能混合使用 NSLayoutDimension(宽度和高度)和 NSLayoutYAxisAnchor(X 和 Y)


这是它在设计中的样子:

您可以在 swift

中这样做
override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        let yConstraint = NSLayoutConstraint(item: toastView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: view.bounds.height * 0.8 )
        NSLayoutConstraint.activateConstraints([yConstraint])
    }

Objective c

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    NSLayoutConstraint *topAnchorConstraint = [NSLayoutConstraint constraintWithItem:toastView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:view attribute:NSLayoutAttributeTop multiplier:1 constant:(view.bounds.size.height * 0.8)];

    [self.view addConstraint:topAnchorConstraint];
}

这里的技巧是设置 toastViewtop 等于 self.viewbottom 乘数 of 0.8:

Objective-C:

[NSLayoutConstraint constraintWithItem: toastView attribute: NSLayoutAttributeTop
    relatedBy: NSLayoutRelationEqual toItem: self.view
    attribute: NSLayoutAttributeBottom multiplier: 0.8 constant: 0].active = YES;

Swift:

NSLayoutConstraint(item: toastView, attribute: .top, relatedBy: .equal,
  toItem: self.view, attribute: .bottom, multiplier: 0.8, constant: 0).isActive = true