给定下图:
三个标签:“今天、平均、上周”在我的 ViewController 中动态定位。当应用程序部署到其他设备(即 iPhone 6 Plus)但位置不正确时,这会成为一个问题。
我知道可以使用 AutoLayout,但是我想使用用于生成 3 个事件栏的库来正确定位它们。
我使用的库是:CHCircleGauge .
我尝试将以下内容添加到该库中,但不确定要使用何种约束将它们定位在您在此图像中看到的位置。
这是我目前使用的代码,即 same code用于将标签“6hrs”水平和垂直居中放置。
NSDictionary *valueLabelDictionary = @{@"valueText" : self.valueTextLabel};
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[valueText]|" options:0 metrics:nil views:valueLabelDictionary]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[valueText]|" options:0 metrics:nil views:valueLabelDictionary]];
我只是简单地添加了以下内容,以至少能够使用动态约束并成功地将标签放置在同一个位置。但问题是我不太确定如何像上图那样完美地定位它们。
NSDictionary *titleLabelDictionary = @{@"titleText" : self.titleTextLabel};
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[titleText]|" options:0 metrics:nil views:titleLabelDictionary]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[titleText]|" options:0 metrics:nil views:titleLabelDictionary]];
如有任何帮助,我们将不胜感激。我仍在努力了解 AutoLayout 和约束的工作原理。
更新:
为了显示三个环,我使用以下内容:
var barView1 = CHCircleGaugeView(frame: CGRectMake(0, 0, 245, 245))
barView1.center = CGPointMake(self.gaugeView.frame.size.width / 2, self.gaugeView.frame.size.height / 2)
barView1.gaugeWidth = 16
barView1.gaugeTintColor = UIColor(red: 255/255, green: 202/255, blue: 76/255, alpha: 1)
barView1.trackWidth = barView1.gaugeWidth
barView1.trackTintColor = UIColor(red: 255/255, green: 202/255, blue: 76/255, alpha: 0.1)
self.gaugeView.addSubview(barView1)
barView1.setValue(0.10, animated: true)
然后我简单地添加了两个更小的尺寸(以 gaugeView
为中心)以适应较大的环。
更新 2:
我最终使用了以下带有一些constant
填充的代码:
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.titleTextLabel
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:-9.0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self.titleTextLabel
attribute:NSLayoutAttributeRight
relatedBy:NSLayoutRelationEqual
toItem:self
attribute:NSLayoutAttributeCenterX
multiplier:1.0
constant:-14.0]];
最佳答案
看来您是自动布局的新手,所以我会尽力为您指明正确的方向,但不会全部泄露。
垂直约束
将每个标签的 Y 约束到环的顶部而不是中心。将每个标签的顶部约束的 constant
设置得略有不同,这样它们就会堆叠在一起。 常量
应该是 trackWidth * (labelIndexNumber)
。所以它们最终会是 0
、16
和 32
。
这样,如果您更改 trackWidth
,您的标签将自动调整。您可能需要稍微调整一下我的数字以获得正确的填充。
水平约束
将每个标签的右侧限制在圆形 View 的中心。我认为您不能为此使用 VFL;你必须使用冗长的 [NSLayoutConstraint constraintWithItem:...
语法。
标签设置
您的标签文本应右对齐。根据您的其他 View ,您可能需要增加水平压缩阻力,但如果可以,请避免这样做。
关于ios - 在 UIView 中定位 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28468939/