如何在UIView上居中放置一个UILabel
我怎样才能在UIView UILabel居中? 我正在使用下面的代码
float width = weatherView.bounds.size.width; float height = weatherView.bounds.size.height; [self.label setFrame:CGRectMake(width-100,height-100, 100, 100)];
怎么样:
[self.label setCenter:view.center];
如果标签是视图的子视图:
[self.label setCenter:CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2)]
除非标签和视图具有相同的超视图,否则不要使用view.center
。
如果没有即时连接,则必须将视图的中心转换为标签父级的坐标空间。 那么你可以使用PengOne的转换点。
使用NSTextAlignmentCenter,如果你已经设置的标签,你想要中心其内容。
cell.menuLabel.textAlignment = NSTextAlignmentCenter;
更好的解决办法是:
首先:如果你正在以编程的方式做这个,你需要使用框架和一些自定义进行初始化:
// 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];
第二:如果一个标签是你正在尝试居中的,你可以在setNumberOflines
select器调用和赋值0 value
之后运行它,你的文本将包含所有需要的行,调用sizeToFit
方法来定制,最后:
[self.label setCenter: CGPointMake(self.view.center.x, self.label.center.y)];
这将only the X axis
中心, Y axis
将在帧初始化期间保持您所需的状态。
PS:这也是有效的,如果不是一个UILabel
但取决于你正在使用的控制将需要另一个简单的定制或两者都没有,如果你只想以编程为中心,但deviseinterface builder
,只需要运行second code
。
像这样的东西应该做的诀窍…确保您的标签设置为居中alignment,足够大/宽处理您的文本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)];
我认为应该做你所要求的。
PengOne / Alex Lockwood的答案简单而有用。 如果您打算支持旋转,请添加以下内容以保持居中:
[self.myLabel setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
如果您的UILabel通过.xib添加或者以编程方式添加,则有两种可能性。
如果第一种情况,即通过.xib添加,那么你可以使用“排列”属性从xib文件大小检查器选项卡中设置位置
如果第二种情况持续,那么你可以设置为— [self.label setCenter:view.center];