2011-10-18 58 views
0

我正在做應用程序,其中我採取了兩個視圖縱向和橫向。我正在創建一個標籤,並通過參數傳遞來調用它。因爲我希望在landscapeView中更改標籤的位置,所以我採用了兩個視圖。相反,我想在單視圖中執行此操作,而不是使用兩個視圖意見我想只有一個視圖,並在縱向和橫向相應地設置標籤的位置。如何在視圖中設置從縱向到橫向的標籤位置

所以請建議我如何只有一個視圖,並根據視圖更改textLabel位置。請向我推薦示例代碼。

目前我使用下面的代碼

[self.portraitView addSubview:[self createLabel:CGRectMake(450,140,60,20):@"Ratings:"]];  
[self.landscapeView addSubview:[self createLabel:CGRectMake(600,140,60,20):@"Ratings:"]]; 

-(UILabel*)createLabel:(CGRect)frame :(NSString*)labelTitle { 
    UILabel *myLabel = [[UILabel alloc] initWithFrame:frame]; 
    [UIFont fontWithName:@"Arial" size:13]; 
    myLabel.text = labelTitle;  
} 

回答

0
  1. 通過在你的.h文件中聲明它,使你的UILabel * myLabel成爲一個類變量。
  2. 根據正確的設備方向,在viewController的viewDidLoad方法中調用createLabel方法。

- (無效)viewDidLoad中

{ 
     UIDeviceOrientation orientation = [UIDevice currentDevice].orientation 

if(orientation == UIDeviceOrientationPortrait) 
      CGRect frame = CGRectMake(450,140,60,20); 
else 
      CGRect frame = CGRectMake(600,140,60,20); 

     myLabel = [[UILabel alloc] initWithFrame:frame]; 
     [UIFont fontWithName:@"Arial" size:13]; 
     myLabel.text = labelTitle;  
} 
  1. 復位幀在該方法中

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{ 
    if(interfaceOrientation == UIInterfaceOrientationLandScape) 
      {  
       mylabel.frame = CGRectMake(600,140,60,20); //your landscape frame 
       mylabel.text = @"Ratings:"; 
      } 
    else 
     { 
      mylabel.frame = CGRectMake(450,140,60,20); // your portrait frame 
      mylabel.text = @"Ratings:"; 
     } 
} 

您將需要爲了涵蓋這種方法中所有可能的方向,挖一點點。

乾杯!

+0

如果聲明Wat代碼我應該添加?給我示例代碼 – crazy2431

+0

如果問題仍然存在,請接受解決問題或更新評論的答案。 – SayeedHussain

+0

謝謝你的迴應...但它顯示未使用的變量框架和LableTitle未聲明...而且我使用參數傳遞在我的代碼中,因爲..我需要在我的視圖中創建許多標籤文本..所以我使用參數傳遞,因爲我有許多其他文本要手動創建.. – crazy2431

0

在代碼中有一個名爲

 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
if(interfaceOrientation == UIInterfaceOrientationLandScape) 
//set label frame here 
} 
+0

[self.view addSubview:[self createLabel:CGRectMake(650,170,60,20):@「Reviews:」]];我應該把上面的代碼放在這裏嗎?還有它給出警告以返回一個值......上面的代碼是正確的還是shd我只是設置了框架..? – crazy2431

0

在你的ViewController以下兩種方法實現方法。

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration 

willRotateToInterfaceOrientation:duration:方法,設置所需幀到標籤實例。

+0

好吧我在哪裏添加下面的代碼[自我。查看addSubview:[self createLabel:CGRectMake(650,140,​​60,20):@「Ratings:」]]; – crazy2431

+0

請爲UILabel創建一個班級成員。分配該實例並將其作爲子視圖添加到主視圖。旋轉時,只需將框架設置爲UILabel實例。 – Ilanchezhian

+0

其實我不想創建一個單一的文本。在我的應用程序中,我將在不同的框架位置創建10個標籤文本..因此,我使用上述代碼中的參數傳遞..但爲什麼需要爲UILabel創建一個類成員? – crazy2431

0

您應該在UILabel的超級視圖的layoutSubviews方法中設置標籤框,並檢查超級視圖邊界或界面方向以確定標籤的相應框架。如果您還正確使用UILabel上的autoresizingMask,則轉換將會很好地生成動畫。

另外:爲什麼你使用兩個視圖?而不是對一個應用不同的佈局?

+0

我可以有示例代碼,因爲我是新來的我是新的iphone開發 – crazy2431

相關問題