gpt4 book ai didi

ios - 从 anchor 约束读取 CGFloat

转载 作者:行者123 更新时间:2023-11-29 11:40:34 31 4
gpt4 key购买 nike

我创建了一个 UIView,然后添加了 Anchor 约束,但是当我想读取值时遇到了问题......

在这种情况下,如您所见,我创建了一个 NSLayoutConstraint 属性来获取我的 uiview 的 anchor 宽度...然后我创建了一个包含约束的 CGFloat,但我的 NSLog 总是返回零值。

我哪里错了?如何获取分配给 anchor 的 UIView 的宽度值?

 UIView *trackLine = [[UIView alloc] init];
trackLine.backgroundColor = [self trackLineColor];
trackLine.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:trackLine];

[trackLine.topAnchor constraintEqualToAnchor:mediaTitle.bottomAnchor constant:25].active = YES;
[trackLine.rightAnchor constraintEqualToAnchor:self.rightAnchor].active = YES;
[trackLine.heightAnchor constraintEqualToConstant:1].active = YES;
self.width = [trackLine.widthAnchor constraintEqualToAnchor:self.widthAnchor multiplier:.8];
self.width.active = YES;

CGFloat trackLineLenght = self.width.constant;
NSLog(@"TRACK LINE %f", trackLineLenght );

NSLog 结果:

**2017-10-21 17:10:35.096562+0200  [5501:1994879] TRACK LINE 0.000000**

最佳答案

好的 - 有点困惑......

首先,不要使用“width”作为属性名称...非常困惑,因为 width 已经在很多地方使用了。

那么,假设您有:

    @property NSLayoutConstraint *trackLineWidthConstraint;

.widthAnchor 在“ anchor 的宽度是多少”方面并没有真正的宽度。您定义约束的方式:

    self.trackLineWidthConstraint = [trackLine.widthAnchor constraintEqualToAnchor:self.widthAnchor multiplier:.8];

表示“将 .trackLineWidthConstraint 属性设置为 self 宽度的 80%。因此,每当 self 的实际宽度发生变化时, trackLine View 的实际宽度将更改为新宽度的 80%。

.constant 为零。如果它不是零,则该值将在 计算 80% 后加上。例如:

self.trackLineWidthConstraint = [trackLine.widthAnchor constraintEqualToAnchor:self.widthAnchor multiplier:.8];
// if self is 200-pts wide, trackLine will be 160-pts

self.trackLineWidthConstraint.constant = 10
// trackLine width is now (200 * 0.8) + 10, or 170-pts

如果你想得到trackLine当前的width,你可以从它的.frame中得到(自动布局完成后).

希望这不会让它变得更加困惑 :)

关于ios - 从 anchor 约束读取 CGFloat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46864781/

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