我正在尝试通过UILabel
循环创建for
,该循环从NSInteger
获取NSArray
。循环工作正常,但我看不到所有顶点一个在另一个下面。我肯定错了一些约束。你能救我吗?
根据此代码,我发布了如何解决NSLayoutConstraint
循环中的for
问题?
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;
}
答案 0 :(得分:1)
我收集到的问题是垂直标记左轴。
如果您的目标是向左边添加标签,则可以将centerY
约束设置为其超级视图centerY
的倍数。唯一的诀窍是它对于0
的乘数不是centerY
,所以对于那个顶级的,我只是将centerY
设置为相等在其超级视图的顶部。因此:
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]];
}
}
收率:
显然,我没有绘制任何图表,但这显示了如果给定图表图表区域,您可以使用乘数来指示标签的位置。