本篇將介紹了Hello World程序的分析代碼,也就是到底這個程序是怎么say Hello的.本文非常適合尚未入門的開發者,希望各位iPhone應用程序開發的初學者喜歡。
每個學習程序開發的第一個程序都是“Hello World”,作為剛剛入門的iPhone應用程序開發者,掌握“Hello World”的分析代碼是十分重要的。本篇將介紹了Hello World程序的分析代碼,也就是到底這個程序是怎么say Hello的。
這個程序基本的運行順序是:載入窗口(UIWindow)->載入自定義的界面(MyViewController),而各種消息的處理均在自定義的界面當中.而程序的設計遵循了MVC(Model-View-Controller)方法,也就是界面和程序是分開做的,通過controller聯接彼此
首先看窗口.在 HelloWorldAppDelegate.h 文件當中有這樣兩行:
其中第一行定義了程序的窗口,第二行定義了我們自己的界面.在 HelloWorldAppDelegate.m 文件中,函數
- IBOutletUIWindow*window;
- MyViewController*myViewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application 是iPhone開發者經常要打交道的一個,定義了程序啟動后要做的工作.這幾行程序的任務是:指定 myViewController 為子界面,
- MyViewController* aViewController =[[MyViewControlleralloc]initWithNibName:@”HelloWorld”bundle:[NSBundlemainBundle]];
- self.myViewController = aViewController ;
- [aViewControllerrelease];
并把子界面顯示到上面來.
- UIView* controllersView =[myViewControllerview];
- [windowaddSubview:controllersView];
- [windowmakeKeyAndVisible];
前面提到了,程序設計遵循了MVC方法,但我們還沒介紹代碼和界面之間是怎么聯系的,也就是說,我們說了程序的UIWindow和view controller要干什么什么,也畫出了界面,可iPhone怎么知道哪個類對應哪個界面呢?這個是在IB(Interface Builder)中完成的.請雙擊 HelloWorld.xib 打開IB.下面看的就是我們的界面.
點到File’s Owner,在Identity Viewer中,注意Class為MyViewController,這就定義了Model和View之間的對應關系.在同一個xib文件中,File’s Owner設定為一個類,并指向其View,該對應關系就建立好了.
在 MyViewController.m 文件中,
- -(void)touchesBegan:(NSSet*)toucheswithEvent:(UIEvent*)event
- {
- //Dismissthekeyboardwhentheviewoutsidethetextfieldistouched.
- [textFieldresignFirstResponder];
- //Revertthetextfieldtothepreviousvalue.
- textField.text = self .string;
- [supertouchesBegan:toucheswithEvent:event];
- }
的作用是:對觸摸做出響應.當觸摸在鍵盤外時,通過 resignFirstResponder 撤銷鍵盤.
- -(BOOL)textFieldShouldReturn:(UITextField*)theTextField{
- //Whentheuserpressesreturn,takefocusawayfromthetextfieldsothatthekeyboardisdismissed.
- if( theTextField ==textField){
- [textFieldresignFirstResponder];
- //Invokethemethodthatchangesthegreeting.
- [selfupdateString];
- }
- returnYES;
- }
作用是:當輸入完文字并按Return后,隱藏鍵盤,并調用updateString命令來更新顯示.這個命令如下:
- -(void)updateString{
- //Storethetextofthetextfieldinthe‘string’instancevariable.
- self.string = textField .text;
- //Setthetextofthelabeltothevalueofthe‘string’instancevariable.
- label.text = self .string;
- }
簡單的說就是用輸入的文字來替換標簽原來的文字以更新顯示.
好了,關于Hello World的分析代碼就介紹到這,主要語句的功能都解說到了.希望大家喜歡。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
