当我使用我的网址方案启动应用程序时,我正在努力预填充文本字段。当应用程序在没有内存的情况下启动时,该值未被设置(或者我认为被viewDidLoad
或类似的推翻)。
我正在采取的捷径如下:
// AppDelegate.m
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
UINavigationController *nav = (UINavigationController *)[[application keyWindow] rootViewController];
MainViewController *main = (MainViewController *)[nav topViewController];
[main setLabelText:@"this should be shown on screen"];
return YES;
}
ViewController
位于UINavigationController
// MainViewController.m
@interface MainViewController ()
@property (weak, nonatomic) IBOutlet UILabel *someLabel;
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.someLabel.text = @"this is actually shown on screen";
}
- (void)setLabelText:(NSString *)text
{
self.someLabel.text = text;
}
@end
因此标签显示“这实际上显示在屏幕上”,而不是我在AppDelegate
中设置的文字。设置断点时,我认为原因相当明显,因为viewDidLoad
之后会调用setLabelText
。
是否有更强大的路径从我自定义的url方案中预填充文本字段?
答案 0 :(得分:1)
试试这个:
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
UINavigationController *nav = (UINavigationController *)[[application keyWindow] rootViewController];
MainViewController *main = (MainViewController *)[nav topViewController];
main.view;
[main setLabelText:@"this should be shown on screen"];
return YES;
}
视图是延迟加载的,因此它将在第一次需要时加载。
答案 1 :(得分:1)
原因是在调用视图控制器的setLabelText:
方法之前从app委托调用viewDidLoad
。你需要做的是在视图控制器的属性中保留字符串的副本,然后在viewDidLoad
的标签上设置它:
部首:
@interface MainViewController
@property (nonatomic, copy) NSString *stringToSet;
@end
实现:
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
if (self.stringToSet) {
self.someLabel.text = self.stringToSet;
} else {
self.someLabel.text = @"Some default string";
}
}
@end
App Delegate:
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
UINavigationController *nav = (UINavigationController *)[[application keyWindow] rootViewController];
MainViewController *main = (MainViewController *)[nav topViewController];
[main setStringToSet:@"this should be shown on screen"];
return YES;
}