官方描述:
HelloWorld demonstrates how to use a keyboard to enter text into a text field and how to display the text in a label.
適用層級:
入門級
這個是最初級的一個例子代碼,所以做為第一個研究的對象,如果你是一個有一定工作經驗的開發人員,請忽略之。
這個工程中需要注意以下幾個地方。
1.這個工程是一個Empty Application工程,不是一個Single View Application工程,雖然運行後看起來象一個Single
View Application工程,
2.建立一個Empty Application工程後,手動加入一個MyViewController類,繼承自UIViewController,同時需要選中With
XIB for user interface。你自己做的時候會發現產生的檔案目錄和例子中不同,請忽略這個,例子是Xcode的曆史版本產生的。
3.在例子中,類名是MyViewController,xib檔案的名字是HelloWorld.xib,在我們自己建立的工程中,類名和xib檔案的名字相同。我們的方式會更方便一些。
當然我們需要改寫HelloWorldAppDelegate類中的函數applicationDidFinishLaunching中的第一行
MyViewController *aViewController = [[MyViewControlleralloc]
initWithNibName:@"HelloWorld"bundle:[NSBundlemainBundle]];
更改為
MyViewController *aViewController = [[MyViewControlleralloc]
initWithNibName:@"MyViewController"bundle:[NSBundlemainBundle]];
4.如果你使用了分別建立類和xib檔案,類名為MyViewController,而xib檔案名稱為HelloWorld.xib,那麼必須自己修改xib檔案。開啟HelloWorld.xib,
選擇File's Owner,在Utility area部分選擇Identity inspector,在Custom Class下面修改Class中的內容,修改為MyViewController,這樣的話,HelloWorldAppDelegate類中的函數applicationDidFinishLaunching中的第一行就不需要再修改了。
在Utility area上選擇Attributes部分,Simulated Metrics裡面的Status Bar上,選擇None.
右鍵點擊View上,選擇New Referencing Outlet後面的圓點,拖拽到File's Owner上鬆手後,點擊出現的view,儲存xib檔案即可。
5.在上面的xib中的view上添加三個控制項,一個是Image view,一個Label,一個是Text Field,同時為後兩個添加IBOutlet的指標。
關於添加IBOutlet的指標,在Xcode4.0中有了新的方式。過去的方式,我就不在這裡介紹了,比較的麻煩。
確保Assistant Editor地區出現,並且是MyViewController.h檔案的內容。
在Text Field上點擊右鍵,點中New Reference Outlet後面的圓點,拖拽到Assistant Editor地區的MyViewController類的聲明中,鬆開後,在彈出對話方塊中輸入textField,斷行符號即可。
同樣的方式也可以快速設定IBAction。
6.在HelloWorldAppDelegate中的applicationDidFinishLaunching函數中:
[[UIApplicationsharedApplication]
setStatusBarStyle:UIStatusBarStyleBlackOpaque];
這行代碼是設定iOS裝置的狀態列在程式運行起來後的呈現方式的,這樣設定是呈現為黑色底。預設的灰色底。
7.UITextFieldDelegate的使用
Text Field在輸入模式下,按斷行符號,軟鍵盤並不會消失,需要我們實現UITextFieldDelegate中的一個函數,並設定所有在viewcontroller中的Text Field的代理都是這個viewcontroller。
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[theTextFieldresignFirstResponder];
returnYES;
}
這個函數在鍵盤消失的時候會被調用。
8.例子程式中,點擊介面上任何其他地方,軟鍵盤也會消失,這個就是下面這個函數起的作用
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// Dismiss the keyboard when the view outside the text field is touched.
[textFieldresignFirstResponder];
// Revert the text field to the previous value.
textField.text =self.string;
[supertouchesBegan:touches
withEvent:event];
}
任何view,viewcontroller都可以重寫下面四個函數來響應手指事件。
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
當然在iOS3.2後,增加了更多的手指事件。