gpt4 book ai didi

ios - 如何将此 UILabel 代码放在我的 AppDelegate 之外?

转载 作者:行者123 更新时间:2023-11-29 04:32:38 25 4
gpt4 key购买 nike

我已经启动了一个新的 iOS“空应用程序”模板项目。当我将此代码放入 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];

这是我尝试放入其他类(class)的内容:

+ (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] 在您的代码中返回 nil,因为您在 UIWindow 的 makeKeyAndVisible 方法被调用之前调用了 addHello 方法。我想知道这是否可行:

在您的 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];
}

关于ios - 如何将此 UILabel 代码放在我的 AppDelegate 之外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11518330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com