2012-07-23 65 views
0

我問過一個類似於以前的問題,首先得到了很多答案,謝謝他們,但是由於項目的複雜性,我不明白答案,因此我決定再次提問以非常簡單的形式。IOS製作按鈕在視圖控制器之間工作

我在viewcontrollerA一個按鈕,我想該按鈕上的標籤是在viewcontrollerB.Its一個簡單的一個按鈕,將設置標籤文本上B.

用戶打開寫應用

點擊頁面在按鈕A

第二頁出現,並在該標籤頁文本由label.text代碼中設置視圖 - 控制一來它調用的代碼

或者我可以從B中調用A的代碼,只要我做出它就不重要。我可以用buton打開另一個viewcontrorrs,所以你不需要解釋它。

此外,如果周圍,只要它們是簡單的,我可以做他們too.Maybe我在其他地方寫的代碼,並從A和B.

叫它任何其他方式

請解釋它一步幹,因爲我有關於目標C和xcode的小知識。

我問這個問題了解viewcontrollers之間的連接。在現實中,我會讓該按鈕在第二頁顯示一個隨機數,但它不重要,因爲如果我學會做簡單的連接,我可以做其餘的。

+0

你說「第二頁出現」。這是一個重要的細節......這是怎麼發生的?你需要的答案是不同的,取決於是否存在涉及到的代碼或代碼中的某些事情。 – 2012-07-23 21:46:42

回答

0

在您的操作中,您需要引用第二個視圖控制器。例如

- (IBAction)buttonAClicked:(id)sender { 
    ViewController2 *vc2 = [[ViewController2 alloc] initWithNibName:@"ViewController2" bundle:nil]; 
    [self.navigationController pushViewController:vc2 animated:YES]; 
    vc2.someVariable = @"This is random text"; 
    [vc2.someButton setTitle:@"Some button text" forControlState:UIControlStateNormal]; 
} 

這顯示瞭如何創建第二個視圖控制器,更改兩個屬性,然後將其推送。

+0

我把我的第一視圖controlelr命名爲Ru1,第二個是Ru2,所以我想我會把這個ru1.h放在這個代碼中寫下我的viewcontroller的名字。 但是,什麼是vc2我想你分配了一個名字它的oke,但是它破壞了我的其他連接從故事板按鈕點擊等爲ru1 ru2 – user1546565 2012-07-23 21:49:53

+0

如果你正在嘗試與故事板做到這一點。你需要命名segue,然後在 - (void)prepareForSegue:(UIStoryboardSegue *)中執行此操作。segue sender:(id)發送方法 – 2012-07-23 21:53:08

+0

在哪裏應該將此代碼寫入第一個viewcontroller.h或第二個? – user1546565 2012-07-23 21:59:44

0

在您的第二視圖控制器創建一個名爲theText屬性,該屬性是一個NSString然後在viewDidLoad分配label.textNSString;

- (void)viewDidLoad 
{ 
    if(self.theText) 
     self.label.text = self.theText; 
} 

現在使用你的第一個視圖控制器在第二個視圖控制器中設置theText

如果您使用的是賽格瑞使用prepareForSegue

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if([[segue identifier] isEqualToString:@"Second View Segue"]) 
    { 
     SecondViewController *theController = segue.destinationViewController; 
     theController.theText = @"Some text"; 
    } 
} 

如果您正在使用某種模式介紹:

SecondViewController *theController = [[SecondViewController alloc] init]; 
theController.theText = @"Some text"; 
[self presentModalViewController:theController animated:YES]; 

,或者如果您使用的是導航控制器:

SecondViewController *theController = [[SecondViewController alloc] init]; 
theController.theText = @"Some text"; 
[self.navigationController pushViewController:theController animated:YES]; 

因此,您的第一個視圖控制器將設置NSString屬性在第二種情況下,第二種設置UILabel等於NSString。你不能設置一個UILabel文本第二視圖控制器被加載之前,所以是這樣的:

SecondViewController *theController = [[SecondViewController alloc] init]; 
theController.label.text = @"Some text"; 
[self.navigationController pushViewController:theController animated:YES]; 

將無法​​正常工作,因爲直到視圖被加載,你不能設置文本標籤。

希望有所幫助。

相關問題