IOS代码实现Hello World

来源:互联网 发布:网络小组组长和副组长 编辑:程序博客网 时间:2024/05/02 15:52

前面写的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下载

http://download.csdn.net/detail/qq5306546/4824578