2013-02-03 18 views
0

我在定位視圖頂部的標籤時遇到了一些麻煩,因此它居中。但是,由於我使用日期,字符串的寬度會有所不同。我也注意到,在3.5英寸的屏幕上,文字不適合。我在標籤的兩側也有兩個圖像按鈕。Obj-C,頂部居中視圖上的標籤/

所以我需要一個保證金。

更爲複雜的是,該視圖只顯示景觀,所以左邊是頂等

ViewController *nextController = [[ViewController alloc] 
       initWithNibName:@"View" bundle:nil]; 
CGAffineTransform newTransform = CGAffineTransformMake(0.0,1.0,-1.0,0.0,0.0,0.0);   
nextController.view.transform = newTransform; 
nextController.hidesBottomBarWhenPushed = YES; 

我想所有我需要做的是......

int margin = 50; 
lblTitle.frame = CGRectMake(margin, 2, th - (margin * 2), 22); 

但這並不奏效。 這幾乎就像在左邊添加狀態欄的高度,但狀態欄是可見的。我做了很多次嘗試,不知道我做錯了什麼。

lblTitle = [[UILabel alloc] initWithFrame:CGRectZero]; 
lblTitle.text = [NSString stringWithFormat:@"%@ - from %@ to %@", 
         strChartType, displayStartDate, displayEndDate]; 

int th = self.view.frame.size.height; 
//int th = self.view.bounds.size.height; 

lblTitle.frame = CGRectMake(0, 2, th, 22); // x, y, w, h 

//[lblTitle setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | 
      UIViewAutoresizingFlexibleRightMargin]; 

//lblTitle.center = CGPointMake(self.view.bounds.size.width/2, 10); 

[lblTitle setTextAlignment:UITextAlignmentCenter]; 
lblTitle.font = [UIFont boldSystemFontOfSize:14]; 
lblTitle.adjustsFontSizeToFitWidth = FALSE; 

lblTitle.backgroundColor = [UIColor yellowColor]; 

[self.view addSubview:lblTitle]; 
+0

'CGRectGetMidX()'和'CGRectGetMidY()'應該是有幫助的 –

+0

什麼是評估對象,你認爲它應該是什麼? – Joel

回答

0

您可以獲取屏幕邊界,然後減去狀態欄的高度以獲取標籤寬度。

float screenHeight = [UIScreen mainScreen].bounds.size.height; 
float statusBarHeight = ([UIApplication sharedApplication].statusBarFrame.size.height < [UIApplication sharedApplication].statusBarFrame.size.width) ? [UIApplication sharedApplication].statusBarFrame.size.height : [UIApplication sharedApplication].statusBarFrame.size.width; 
float labelWidth = screenHeight - statusBarHeight; 

注:mainScreen界限,始終會在肖像模式,所以你不必擔心方向,但statusBarFrame可以旋轉,所以你需要檢查框的寬度或高度是正確的值使用。

+0

嗨@Joel,我從寬度上取下了100,這與上面的圖像一樣。實際上,我產生的效果相同。 – Jules

+0

如果不減去100,它是否如預期的那樣從頂部到底部?其他事情正在發生。你需要記錄所有的框架尺寸(視圖,標籤等),看看哪一個產生了意想不到的結果。 – Joel

+0

是的,沒有100 – Jules