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条回答
Lonely孤独者°
2楼-- · 2019-01-31 12:19

PengOne / Alex Lockwood's answer is simple and useful. If you intend to support rotation, add the following to keep it centered:

[self.myLabel setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
查看更多
聊天终结者
3楼-- · 2019-01-31 12:21

Use NSTextAlignmentCenter if what you have is the label already set and you want to center its content.

cell.menuLabel.textAlignment = NSTextAlignmentCenter;
查看更多
看我几分像从前
4楼-- · 2019-01-31 12:22

If the label is a subview of view:

[self.label setCenter:CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2)]

Don't use view.center unless the label and view have the same superview.

If there is no immediate connection, then you'll have to transform view's center to the coordinate space of label's parent. Then you could use PengOne's answer with the transformed point.

查看更多
Anthone
5楼-- · 2019-01-31 12:29

There are two possibility if your UILabel is added via .xib or else added programmatically .

If first case i.e added via .xib then you can set the position from xib file size inspector tab with the 'Arrange' property

And if second case persist then you can set as --- [self.label setCenter:view.center];

查看更多
可以哭但决不认输i
6楼-- · 2019-01-31 12:41

Something like this should do the trick... Make sure that your label is set to have centered alignment and is sufficiently big/wide to handle your text string.

float viewWidth = weatherView.frame.size.width;
float viewHeight = weatherView.frame.size.height;
float labelWidth = label.frame.size.width;
float labelHeight = label.frame.size.height;

float xpos = (viewWidth/2.0f) - (labelWidth/2.0f);
float ypos = (viewHeight/2.0f) - (labelHeight/2.0f);

[label setFrame:CGRectMake(xpos,ypos,labelWidth,labelHeight)];

I think that should do what you are asking for.

查看更多
Summer. ? 凉城
7楼-- · 2019-01-31 12:43

How about:

[self.label setCenter:view.center];
查看更多
登录 后发表回答