如何居中放置在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)];
如何居中放置在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];
像這樣的東西應該做的伎倆...... 確保您的標籤設置爲已居中對齊,足夠大/寬處理您的文本字符串。
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)];
我認爲應該做你所要求的。
我不知道標籤的大小,因此我使用siteToFit方法。 –
只要你在標籤上做了任何初始化操作,上面的代碼仍然可以工作 –
如果標籤的視圖子視圖:
[self.label setCenter:CGPointMake(view.frame.size.width/2, view.frame.size.height/2)]
不要使用view.center
除非標籤,查看有沒有相同的上海華。
如果沒有即時連接,則必須將視圖的中心轉換爲標籤父級的座標空間。然後,您可以使用PengOne的轉換點。
更好更多鈔票的解決方案是:
第一:如果你正在做這個程序,你需要與框架進行初始化和一些自定義:
// 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
選擇器調用和0 value
賦值之後運行這個,你的文本將會有所有需要的行,並且調用sizeToFit
方法有很好的定製,最後是:
[self.label setCenter: CGPointMake(self.view.center.x, self.label.center.y)];
這將圍繞only the X axis
和Y axis
就會留在這裏。你在框架初始化所需。
PS:這也是有效的,如果不是UILabel
而是取決於你使用需要另一個簡單的定製或者沒有控制,如果你只是想中心編程,但interface builder
設計,只需要運行second code
。
'self.view.frame.width'應該是'self.view.frame.size.width' –
如果您的UILabel通過.xib添加或者以編程方式添加,則存在兩種可能性。
如果第一種情況,即通過增加的.xib然後你可以設置從廈門國際銀行文件大小檢查標籤的位置用「排」財產
如果第二種情況仍然存在,那麼你可以設置爲--- [自我。標籤setCenter:view.center];
PengOne/Alex Lockwood的回答很簡單而且有用。如果您打算支持旋轉,添加以下,以保持它爲中心:
[self.myLabel setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
使用NSTextAlignmentCenter如果您有什麼是已經設置標籤,並要居中其內容。
cell.menuLabel.textAlignment = NSTextAlignmentCenter;
這是最好的答案是,將標籤框居中對於文本居中是不夠的,如果您的標籤已經本地化,非常有用! – gabry
我認爲這可能是OP想要做的唯一正確答案。它是我想要做的。 –
該工作,但如果標籤很長,那麼它不居中。它可以向左或向右。我認爲定位取決於uilabel的中心點。 –
呃...只有標籤和視圖是同一視圖的子視圖。如果標籤是視圖的子視圖,則必須忽略該位置並只考慮邊界。 – Eiko
我使用界面設計器(拖放)添加了UILabel。這是否意味着它是視圖的子視圖,我應該使用邊界。 –