2013-11-27 116 views
0

我有兩個視圖控制器'FirstViewController'和'SecondViewController'。從第一個視圖控制器中,它將從文本字段獲取輸入,對其進行處理並在第二個視圖中相應顯示。但是,我直接設置標籤值時遇到問題。IOS Segue無法直接設置標籤

@interface SecondViewController : UIViewController 
    { 
     NSString *numPlate; 
     IBOutlet UILabel *output; 
    }; 
    @property(strong,nonatomic) NSString *numPlate; 
    @property(strong,nonatomic) IBOutlet UILabel *output; 
    @end 

爲FirstViewController.m的主要文件,爲準備賽格瑞是

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if([[segue identifier] isEqualToString:@"Change"]) 
    { 
     SecondViewController *svc = (SecondViewController *)[segue   destinationViewController]; 
     svc.numPlate = input.text; 


     NumberPlate *numPlate=[[NumberPlate alloc]init]; 
     [numPlate setPlate:input.text]; 
     NSInteger flag=[numPlate checkValidity]; 
     if(flag==0) 
     { 
      svc.output.text [email protected]"Invalid License"; 
     } 
     else 
     if([numPlate getArea]==NULL||[numPlate getRegOffice]==NULL) 
     { 
      svc.output.text [email protected]"Data not found"; 
     } 
     else 
     { 
     svc.output.text [email protected]"VALID License"; 
     } 
    } 
    } 

但是,當被執行操作的不working.The標籤不改變。 當我用svc.numPlate代替svc.output.text並在SecondViewController viewDidLoad方法和我用

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    output.text=numPlate; 
} 

一切都很好與此有關。第一種方法有什麼不妥?

回答

1

您將無法直接爲第二個VC UILabel賦值,因爲此時視圖尚未加載到視圖層次結構中。

因此,視圖無法呈現之前分配的值。

另一方面,在NSString中保存值並在viewDidLoad上賦值與現在一樣工作,因爲您的視圖處於視圖層次結構並加載到內存中。

+0

謝謝,有沒有比傳遞數據到字符串更好的方法。 – slaveCoder

+0

@BittuAby在某種意義上說,這是解決方案,而不是通過全局或靜態來傳遞價值。 –

+0

我是ios編程新手。你可以給我一些關於這些主題的教程鏈接。即全局/靜態 – slaveCoder

1

在您推送SecondViewController時,SecondViewController的視圖尚未加載,因此您無法訪問其視圖。您需要在SecondViewController中創建NSString屬性並將字符串傳遞給SecondViewController的NSString對象。然後在SecondViewController的viewDidLoad方法中,使用這些屬性填充標籤(它將在viewDidLoad運行時加載)。

0

控制器的初始化是不同的,它的視圖呈現是不同的過程,即使viewController已初始化其視圖不會因爲推控制器沒有執行和控制器不知道他需要加載視圖..所以我們將數據傳遞給控制器​​,當視圖出現時加載它...像下面的代碼

@interface SecondViewController : UIViewController{ 
    NSString *strMessage; 

} 
@property(nonatomic,retain) NSString *strMessage; 

@end 
SecondViewController.m 

@synthesize strMessage; 

- (void)viewDidLoad { 
Nslog(@"%@",strMessage); 
} 

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if([[segue identifier] isEqualToString:@"Change"]) 
    { 
     SecondViewController *svc = (SecondViewController *)[segue   destinationViewController]; 


    NSString *message = [NSString stringWithFormat:@"Check out %@", nameLb.text]; 
    svc.strMessage=message; 
}