我正在尝试通过 for
循环创建 UILabel
,该循环从 NSArray
获取其 NSInteger
。循环工作正常,但我看不到所有顶点一个接一个。我肯定是有约束的错误。你能帮帮我吗?
根据我发布的这段代码,如何解决 for
循环中的 NSLayoutConstraint
问题?
NSInteger max = [[_yValueArray valueForKeyPath:@"@max.self"] integerValue];
NSInteger min = [[_yValueArray valueForKeyPath:@"@min.self"] integerValue];
for (NSInteger value = max; value >= min; value -=1) {
UILabel *valueLabel = [[UILabel alloc] init];
valueLabel.textColor = [UIColor lightGrayColor];
valueLabel.backgroundColor = [UIColor redColor];
valueLabel.textAlignment = NSTextAlignmentLeft;
valueLabel.font = [UIFont defaultAppFontWithSize:10];
valueLabel.translatesAutoresizingMaskIntoConstraints = NO;
valueLabel.text = [self yValueString:value];
valueLabel.tag = value;
[yAxisView addSubview:valueLabel];
[yAxisView addConstraint:[NSLayoutConstraint constraintWithItem:valueLabel attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:valueLine attribute:NSLayoutAttributeLeft multiplier:1 constant:-2]];
NSLayoutConstraint *topConstraint = [NSLayoutConstraint constraintWithItem:valueLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:yAxisView attribute:NSLayoutAttributeTop multiplier:1 constant:0];
[yAxisView addConstraint:topConstraint];
NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:valueLabel attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:valueLine attribute:NSLayoutAttributeHeight multiplier:1 constant:10];
[yAxisView addConstraint: height];
// topConstraint.constant += height.constant;
}
最佳答案
我收集到的问题是垂直标记左轴。
如果您的目标是向左边缘添加标签,您可以将 centerY
约束设置为其父 View 的 centerY
的倍数。唯一的技巧是它不喜欢 centerY
的乘数 0
,所以对于最上面的一个,我只设置 centerY
等于其父 View 的顶部。因此:
NSInteger max = 10;
for (NSInteger i = 0; i <= max; i++) {
UILabel *label = [[UILabel alloc] init];
label.translatesAutoresizingMaskIntoConstraints = false;
label.text = [NSString stringWithFormat:@"%ld", (long)i];
[self.chartDataView addSubview:label];
CGFloat multiplier = (CGFloat)(max - i) * 2.0 / (CGFloat)max;
[self.chartDataView addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.chartDataView attribute:NSLayoutAttributeLeft multiplier:1 constant:-5]];
if (multiplier == 0) {
[self.chartDataView addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.chartDataView attribute:NSLayoutAttributeTop multiplier:1 constant:0]];
} else {
[self.chartDataView addConstraint:[NSLayoutConstraint constraintWithItem:label attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.chartDataView attribute:NSLayoutAttributeCenterY multiplier:multiplier constant:0]];
}
}
产量:
很明显,我没有绘制任何图表,但这显示了在给定图表图形区域的情况下,您可以如何使用乘数来指示标签的位置。
关于ios - 循环中的 NSLayoutConstraint FOR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46621856/