How to center a UILabel on UIView

2019-01-31 12:07发布

How can I center the UILabel on the UIView? I am using the following code

float width = weatherView.bounds.size.width; 
float height = weatherView.bounds.size.height; 

[self.label setFrame:CGRectMake(width-100,height-100, 100, 100)];

7条回答
Animai°情兽
2楼-- · 2019-01-31 12:43

A better posible solution is:

First: If you are doing this programmatically you'll need to initialize with frame and some customizations:

// Simple example
int yPosition = 10;
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0, yPosition, self.view.frame.size.width, 0)];
[label setText: @"Testing..."];
[label setBackgroundColor: [UIColor clearColor]];
[label setNumberOfLines: 0];
[label sizeToFit];

Second: If a label what you are trying to center you can just run this after setNumberOflines selector called and 0 value assigned, your text will have all lines needed, and sizeToFit method called to have a good customization, and finally:

[self.label setCenter: CGPointMake(self.view.center.x, self.label.center.y)];

This will center only the X axis, and the Y axis will stay as you desired in the frame initialization.

PS: It's also valid if not a UILabel but depends on the control you are using will need another simple customization or neither, and if you only want to center programmatically but interface builder designed, just need to run the second code.

查看更多
登录 后发表回答