IOS Segue无法直接设置标签



我有两个视图控制器"FirstViewController"one_answers"SecondViewController"。从第一个视图控制器,它将从文本字段中获取输入,对其进行处理,并相应地在第二个视图中显示。但我在直接设置标签值时遇到了问题。

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

带有prepare for segue的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  =@"Invalid License";
       }
       else
       if([numPlate getArea]==NULL||[numPlate getRegOffice]==NULL)
       {
            svc.output.text  =@"Data not found";
       }
       else
       {
        svc.output.text  =@"VALID License";
       }
     }
   }

但当动作被执行时,它就不起作用了。标签没有更改。当我使用svc.numPlate而不是svc.output.text时,在SecondViewController视图DidLoad方法中,我使用

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

这一切都很好。第一种方法出了什么问题??

您将无法直接将值分配给第二个VC的UILabel,因为此时视图尚未加载到视图层次结构中。

因此视图无法呈现之前指定的值。

另一方面,在NSString中保持值并在viewDidLoad上分配值,就像现在视图在视图层次结构中并加载到内存中一样。

当您推送SecondViewController时,SecondViewController的视图尚未加载,因此您无法访问其视图。您需要在SecondViewController中创建NSString属性,并将字符串传递给SecondViewController的NSString对象。然后在SecondViewController的viewDidLoad方法中,使用这些属性来填充标签(在viewDidLoad运行时已经加载)。

控制器的初始化是不同的,其视图的呈现也是不同的过程,即使视图已经初始化,控制器也不会初始化其视图,因为推送控制器没有执行,控制器不知道他需要加载视图。。所以我们将数据传递给控制器,并在视图出现时加载。。。如以下代码

@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;
}

最新更新