当我在模拟器中执行下面的代码时,我希望看到红色填满屏幕,但是它全是黑色,为什么?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UIView * myView = [[UIView alloc] initWithFrame:[window bounds]]; [myView setBackgroundColor:[UIColor redColor]]; [window addSubview:myView]; [window makeKeyAndVisible]; return YES; }
如果我添加窗口的初始化,这没有帮助:
window = [[[UIWindow alloc] init] initWithFrame:[[UIScreen mainScreen] bounds]];
在Xcode中创建基于Window的Universal项目之后我开始麻烦了我决定删除iPad / iPhone xib文件和iPhone / iPad应用程序委托文件,这些文件是在项目中自动创建的,而是有一个带有视图的应用程序委托控制器,基于设备以编程方式构建视图.现在我似乎无法显示我在app delegate中创建的简单视图.
编辑:我删除了添加视图,现在将窗口的背景颜色设置为红色.这没有用,但如果我在模拟器中转到桌面并重新打开运行的应用程序,我现在得到一个红色的屏幕.再一次,我很困惑,为什么我第一次启动应用程序时看不到红色.
解决方法
以下是设置非InterfaceBuilder(.xib)通用iOS项目的步骤.
>从项目中删除所有.xib文件
>(可选)创建一个公共Application Delegate类,然后删除AppDelegate_iPad.*和AppDelegate_iPhone.*文件. (在删除之前复制粘贴现有文件中的任何代码)
>更改main.m文件以命名应用程序委托.我选择修改并使用AppDelegate_iPhone作为示例.请参阅文档:UIApplication Reference
// main.m
int main(int argc,char * argv []){
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // Start an iPhone/iPad App using a .xib file (Defaults set in .plist) //int retVal = UIApplicationMain(argc,argv,nil,nil); // Start the iPhone/iPad App programmatically // Set the 3rd argument to nil,to use the default UIApplication // Set the 4th argument to the string name of your AppDelegate class int retVal = UIApplicationMain(argc,@"AppDelegate_iPhone"); [pool release]; return retVal;
}
>更新您的应用程序委托代码.
// AppDelegate_iPhone.m
– (BOOL)应用程序:(UIApplication *)应用程序didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch. NSLog(@"Launch my application iphone"); // Create the window,it's not created without a nib window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Create a subview that is red UIView *myView = [[UIView alloc] initWithFrame:[window bounds]]; [myView setBackgroundColor:[UIColor redColor]]; // Add the subview and release the memory,sicne the window owns it Now [self.window addSubview:myView]; [myView release]; [self.window makeKeyAndVisible]; return YES; }