从锚约束读取 CGFloat

Read CGFloat from Anchor Constraints

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

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

我哪里错了?如何获取分配给锚点的 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" 作为 属性 名称...非常混乱,因为宽度已经在很多地方使用了。

那么,假设您有:

    @property NSLayoutConstraint *trackLineWidthConstraint;

A .widthAnchor 就 "what's the width of the anchor." 而言实际上没有宽度 您定义约束的方式:

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

说“将 .trackLineWidthConstraint 属性 设置为 self 宽度的 80%。因此,每当 self 的实际宽度发生变化时,您的 trackLine 视图将更改为新宽度的 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中得到(在自动布局完成后)。

希望这不会让它变得更加混乱:)