读CGFloat的从Anchor约束
问题描述:
我创建了一个的UIView,然后添加锚点限制,但我有一个问题,当我想读值...读CGFloat的从Anchor约束
在这种情况下,你看到的,我创建了一个NSLayoutConstraint属性得到我的uiview的锚宽度...然后我创建了一个包含约束的CGFloat,但是我的NSLog总是返回一个ZERO值。
我在哪里错了?我怎样才能得到我的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**
答
OK - 有点混乱......
首先,不要使用 “宽度” 作为属性名称...很混乱,因为宽度已经在很多地方使用了。
所以,让我们假设你有:
@property NSLayoutConstraint *trackLineWidthConstraint;
一个.widthAnchor
实际上并没有在条款宽度“什么是锚的宽度。”您要定义约束的方式:
self.trackLineWidthConstraint = [trackLine.widthAnchor constraintEqualToAnchor:self.widthAnchor multiplier:.8];
说“设定的self
的宽度.trackLineWidthConstraint
属性为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
的当前宽度,您可以从.frame
(在自动布局完成后)获取它。
希望,这不只是使它更加混乱:)
什么是'self.widthAnchor'在该点的价值? “自我”可能不具有固有尺寸,其框架尚未设置? – DonMag
@DonMag用几句话我试图使用uiview而不是CALayer来学习本教程,但我仍然得到错误的值,我不知道为什么https://www.raywenderlich.com/36288/how-to-make-一个自定义控件 – kAiN
好吧......所以......就像我在第一个评论中提到的那样...... *那个点上的'self.widthAnchor'的值是多少?* – DonMag