Quick version: Why does the value of a UILabel's "center" property change between when it's Size Attribute is bound to the top of it's parent container and the bottom, and what can I do to change or get around that behavior?
Long version with details: I am drawing a line between two labels like this (the yellow line):
To calculate the end points for the line I am using the center property of the UILabels (in this photo the labels say 2.5kHz and 20 Hz), then + or - half of the label's height. This technique Works good in the example/picture below. However in the design phase where I toggled the screen size to the iPhone5 (taller), I bound the "20 Hz" label to the bottom instead of the top by changing it in the Size Inspect as pictured in the following two images. Note that the origin is still in the upper left in both cases:
This changes how the center property behaves and thus will produce the following line:
Here I have relocated the UILabel just for demonstration. Note that the end of the line should be on the center of the top of the label:
I did a printout of the label's center point. Once while bound to the top, and again to the bottom:
Bound to top {290, 326.5}
Bound to bottom {290, 370.5}
I tried a workaround by using the origin.y and doing an offset from there, but that has the same type of effect.
I desire it to look like this when finished, but on the taller iPhone 5 screen:
Edit: As requested by @ott, adding the code snippet which calculates the end points of the line
- (void)viewDidLoad
{
[super viewDidLoad];
CGPoint begin = self.frequencyMaxLabel.center;
begin.y += self.frequencyMaxLabel.frame.size.height/2.0;
CGPoint end = self.frequencyMinLabel.center;
end.y -= self.frequencyMinLabel.frame.size.height/2.0;
// This is an object of two CGPoints to represent a line
VWWLine* frequenciesLine = [[VWWLine alloc]
initWithBegin:begin
andEnd:end];
// Pass the line to a UIView subclass where it is drawn
[self.configView setLineFrequencies:frequenciesLine];
[frequenciesLine release];
// .... other code truncated for example
}
And the code that draws the line (inside a UIView subclass, self.configView from above snippet)
- (void)drawRect:(CGRect)rect
{
CGContextRef cgContext = UIGraphicsGetCurrentContext();
CGContextBeginPath(cgContext);
CGContextSetLineWidth(cgContext, 2.0f);
CGFloat yellowColor[4] = {1.0, 1.0, 0.0, 1.0};
CGContextSetStrokeColor(cgContext, yellowColor);
[self drawLineWithContext:cgContext
fromPoint:self.lineFrequencies.begin
toPoint:self.lineFrequencies.end];
CGContextStrokePath(cgContext);
//...... truncated. Draw the other lines next
}
You receive the viewDidLoad
message before the system has laid out your views for the current device and interface orientation. Move that code to viewDidLayoutSubviews
.
Also, you might want to check out CAShapeLayer
.