![](/img/trans.png)
[英]How do I put AppDelegate Swift code into Objective-C AppDelegate file and make it work?
[英]How do I put this UILabel code outside of my AppDelegate?
我已经启动了一个新的iOS“ Empty Application
” -template项目。 当我将此代码放入application:didFinishLaunchingWithOptions:
方法中时,它可以正常工作:
CGRect frame = CGRectMake(10, 10, 300, 25);
UILabel *helloLabel = [UILabel new];
[helloLabel setFrame:frame];
helloLabel.text = @"Hello iPhone!";
[self.window addSubview:helloLabel];
但是我真正想做的是在另一个类中创建一个“ addHello”类方法,以便在application:didFinishLaunchingWithOptions:
内容仅仅是:
[MyOtherClass addHello];
这是我尝试放入另一堂课的内容:
+ (void) addHello {
CGRect frame = CGRectMake(10, 10, 300, 25);
UILabel *helloLabel = [UILabel new];
[helloLabel setFrame:frame];
helloLabel.text = @"Hello iPhone!";
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
[window addSubview:helloLabel];
}
但这是行不通的。 我应该做些什么?
我的猜测是,[[UIApplication的sharedApplication] keyWindow]在你的代码回来为零,因为你在呼唤你的addHello方法的UIWindow的makeKeyAndVisible方法尚未调用之前。 我想知道这是否行得通:
在您的appDidFinishLaunching方法中:
[MyOtherClass addHelloWithWindow:self.window];
然后你的MyOtherClass
+ (void) addHelloWithWindow:(UIWindow *)window
{
CGRect frame = CGRectMake(10, 10, 300, 25);
UILabel *helloLabel = [UILabel new];
[helloLabel setFrame:frame];
helloLabel.text = @"Hello iPhone!";
[window addSubview:helloLabel];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.