gpt4 book ai didi

objective-c - NSView 约束 - 如何强制 subview 的纵横比保持不变?

转载 作者:行者123 更新时间:2023-12-03 17:34:41 27 4
gpt4 key购买 nike

执行以下操作时遇到困难:

+-------------------+
| |
| |
| RESIZABLE |
| |
| NSVIEW |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|+-----------------+|
|| ||
|| STATIC ||
|| ||
|| SUBVIEW ||
|| ||
|+-----------------+|
+-------------------+

subview 的宽高比必须保持不变(当用户更改可调整大小的 View 的宽度时)。

我想使用约束来做到这一点,到目前为止我已经做到了:

//This is a snippet of the resizable view class

[self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:subview attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:subview attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];

//This is a snippet of the subview class

[self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:aspectRatio constant:0]];

可调整大小的 View 的框架已初始设置。在这种情况下,不设置 subview 的框架是否有意义?目前,主视图似乎消失了 - 它的宽度开始为零。

我应该如何解决这个问题 - 如果可能的话我很乐意使用约束!

最佳答案

这可以通过在 IB 中设置大部分约束,然后在代码中更改其中之一来完成。静态 subview 应该具有您想要的可调整大小 View 的侧面和底部的任何间距约束,以及固定的高度约束——创建这些约束后,您应该能够删除可调整大小 View 顶部的约束(如果有) 。为高度约束创建一个 IBOutlet,并在如下代码中更改它(heightCon 是我的导出,此代码位于静态 subview 子类中):

- (void)awakeFromNib {
[self removeConstraint:self.heightCon];
self.heightCon = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:.54 constant:0];
[self addConstraint:self.heightCon];
}

0.54 的数字来自于我在 IB 中的初始高宽比。

关于objective-c - NSView 约束 - 如何强制 subview 的纵横比保持不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16521360/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com