前面写的IOS笔记一直都是用Xib文件实现的小Demo开发,但是问了好几个现在正从事IOS开发的朋友,在实际开发,并不是所有的项目都会用Xib来实现的,因为IOS以前的版本不能正常运行,因为还在学习阶段,也没有在真机上测试,所以没法验证。但还是决定要用代码来实现Demo,也可以重新巩固一下先前学习的内容。
通过Xcode的版本更新,先有的实现方法应该有3种。
第一种:通过代码实现
第二种:通过Xib文件实现
第三种:能过Storyboard配置实现
代码实现项目的开发,在开发周期上要慢一点,但是在学习阶段无疑是更好的,让我在学习过程中能记忆更深刻一点
Xib文件相对代码的实现方法,则开发速度上要更快些,也是必须要掌握的
Storyboard这个就更快了,基本上不用关注窗口,整个View业务也像UML图一样,一看就能很清楚
总结我知道的3种方法,就只接上图上代码了。

首先创建一个emtpy application项目,命名为CodeHelloWorld

在创建一个名为MainViewController的Class文件

AppDelegate.h添加代码
#import <UIKit/UIKit.h>
// 引入添加的MainViewController.h
#import "MainViewController.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) MainViewController *mainView;
@end
AppDelegate.m添加代码
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window = _window;
@synthesize mainView = _mainView;
- (void)dealloc
{
[self.window release];
[self.mainView release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.mainView = [[MainViewController alloc] init];
self.window.rootViewController = self.mainView;
[self.window makeKeyAndVisible];
return YES;
}
接下来就是创建当前显示的UIView和UILabel显示Hello World了
打开MainViewController.m文件,添加以下方法
- (void)loadView并在方法内添加以下代码
// 声明一个UIView
UIView *view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
// View的背景设置为白色
view.backgroundColor = [UIColor whiteColor];
self.view = view;
[view release];
CGRect rect = CGRectMake(100, 100, 300, 100);
UILabel *textLabel = [[UILabel alloc] initWithFrame:rect];
textLabel.text = @"Hello World";
textLabel.textColor = [UIColor redColor];
[self.view addSubview:textLabel];
运行项目后,就可以看到神一样的hello world了
DEMO下载
这篇博客介绍了如何在iOS中通过代码实现Hello World应用,探讨了三种实现方法:代码、Xib文件和Storyboard。博主强调在学习阶段代码实现有助于加深理解,而Xib和Storyboard则在开发效率上有优势。文中详细展示了创建empty application项目,创建MainViewController类文件,以及在AppDelegate和MainViewController中添加必要代码的步骤,最终成功运行并显示'Hello World'。
2960

被折叠的 条评论
为什么被折叠?



