我有两个视图控制器'FirstViewController'和'SecondViewController'。从第一个视图控制器,它将从文本字段获取输入,处理它并在第二个视图中相应地显示。但是我在直接设置标签值时遇到了问题。
@interface SecondViewController : UIViewController
{
NSString *numPlate;
IBOutlet UILabel *output;
};
@property(strong,nonatomic) NSString *numPlate;
@property(strong,nonatomic) IBOutlet UILabel *output;
@end
准备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 viewDidLoad方法中使用
- (void)viewDidLoad
{
[super viewDidLoad];
output.text=numPlate;
}
这一切都很好。第一种方法有什么不对?
答案 0 :(得分:1)
当您按下SecondViewController时,SecondViewController的视图尚未加载,因此您无法访问其视图。您需要在SecondViewController中创建NSString属性并将字符串传递给SecondViewController的NSString对象。然后在SecondViewController的viewDidLoad方法中,使用这些属性来填充标签(这些标签将在viewDidLoad运行时加载)。
答案 1 :(得分:1)
此时,您无法将值直接分配给第二个VC 的UILabel
,因为视图尚未加载到视图层次结构。
因此视图无法呈现之前指定的值。
另一方面,保留NSString
中的值并在viewDidLoad
上分配值正在运行,因为现在您的视图位于视图层次结构中并加载到内存中。
答案 2 :(得分: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;
}