【问题标题】:Read CGFloat from Anchor Constraints从锚约束中读取 CGFloat
【发布时间】:2018-04-02 13:13:11
【问题描述】:

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

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

我哪里错了?如何获取分配给锚点的 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**

【问题讨论】:

  • 此时self.widthAnchor 的值是多少? self 是否可能没有固有大小,并且它的框架尚未设置?
  • @DonMag 简而言之,我试图使用 uiview 而不是 CALayer 来遵循本教程,但我仍然得到错误的值,我不知道为什么 raywenderlich.com/36288/how-to-make-a-custom-control
  • 好吧……所以……正如我在第一条评论中所问的那样……那时self.widthAnchor 的价值是多少?
  • nslog 上的光标位置是 20.5 但 self.currentValue 的值是 30

标签: ios uiview anchor nslayoutconstraint cgfloat


【解决方案1】:

好的 - 有点混乱......

首先,不要使用“宽度”作为属性名称...这很混乱,因为宽度已经在很多地方使用了。

所以,假设你有:

    @property NSLayoutConstraint *trackLineWidthConstraint;

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

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

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

.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的当前宽度,你可以从它的.frame得到它(在自动布局完成之后)。

希望这不仅让事情变得更加混乱 :)

【讨论】:

  • 好的,但是自动布局后如何获取框架?为什么当我调用 view.frame.size.width 时从不给我一个值......我在调用框架的位置是否错了?
  • 如果我们可以进行 2 分钟的聊天,我会看到我的代码以了解为什么我的滑块没有响应...我快疯了
  • 在这里加入我的聊天(之前与其他人聊天...)chat.stackoverflow.com/rooms/156596/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-29
  • 2018-04-20
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多