I’m trying to center my UILabel horizontally. This is what it ends up looking like (notice its no center).

ReflectionView *aReflectionView = [[ReflectionView alloc]initWithFrame:CGRectMake(((self.view.bounds.size.width / 2) - 150), 40, 300, 90)];
UILabel *aLabel = [[UILabel alloc]initWithFrame:CGRectMake(((self.view.bounds.size.width / 2) - 150), 0, 300, 90)];
aLabel.textAlignment = UITextAlignmentCenter;
aLabel.text = @"1 lbs";
self.weightLabel = aLabel;
[aReflectionView addSubview:self.weightLabel];
self.weightReflectionView = aReflectionView;
[self.view addSubview:self.weightReflectionView ];
[self.weightReflectionView updateReflection];
The
textAlignmentproperty will align text within the frame of theUILabel, not outside of it. My ASCII skills are a little rusty, but here’s what I mean. Consider the labels below, where the|indicates the left/right edge of the label.Now consider the same label contained within another view, where the outer
[]represent the edges of the containing view, and the inner|represents the edges of the contained label. Notice how the inner label is not exactly centered within its superview, and is slightly pushed to the right (2 spaces away from the left, and 1 space closer to the right).If you want the label to be center aligned within the superview or the screen at all times, you would want to make sure the width of the label matches its container, and then set
textAlignmentto center. Here’s how:This is a common case where you want the subview to match the exact size of the superview. You can use the
boundsproperty to easily do that.As a UI debugging tip, try changing the background of the problematic view (label) to show exactly what area it is taking, which usually helps solving many such problems.