iOS中Xcode和Interface Builder聯合應用 實例操作
iOS中Xcode和Interface Builder聯合應用 實例操作是本文要介紹的內容,剛剛接觸ios有很多地方都還不知道,但對它有這強烈的興趣。現在先總結一下這幾天掌握的東西。要想讓Xcode和Interface Builder同時開發一個應用程序,必須以模版View-Based Application(基于視圖的應用程序)作為應用程序的起點。
1、創建項目
因為使用的測試程序工具是iPhone Simulator,所以在創建項目時選的是iPhone OS的Application,并在右邊的列表中選擇View-Based Application,最好還是勾選Use Core Data for storage這個項。
2、創建輸出和操作
根據應用程序的設計,假設這里要使用三個文本框,兩個文本視圖,一個按鈕。則先在視圖控制器的開頭(在項目中的Class文件下的一個文件)*ViewController.h創建輸出口和操作。在在類內聲明變量:eg:
- @interface *ViewComtroller : UIViewController {
- IBOutlet UITextField *thePlace;
- IBOutlet UITextField *theVerb;
- IBOutlet UITextField *theNumber;
- IBOutlet UITextView *theStory;
- IBOutlet UITextField *theTemplate;
- IBOutlet UIButton *generateStory;
- }
- @propery (retain, nonatomic) UITextField *thePlace;
- @propery (retain, nonatomic) UITextField *theVerb;
- @propery (retain, nonatomic) UITextField *Number;
- @propery (retain, nonatomic) UITextView *theStory;
- @propery (retain, nonatomic) UITextView *theTemplator;
- @propery (retain, nonatomic) UIButton *generateStory;
- -(IBAction) createStory: (id) sender;
- @end
@propery通常有相應的編譯指令@synthesize,所以需要在*.ViewController.m中的編譯指令@implementation后面添加下列紅色字體代碼:
- @implementation *ViewXontroller
- @synthesize thePlace;
- @synthesize theVerb;
- @synthesize theNumber;
- @synthesize theStory;
- @synthesize theTemplate;
- @synthesize generateStory;
到這里,設置已經基本完成了,現在要做的就是對界面的設計了~
3、打開視圖控制器
在項目文檔下的一個名為Resources的文件夾下有一個名為:*ViewController.xib文件,這是一個視圖控制器文件,利用IB(Interface Builder)對界面的設計都是在這個文件下進行的。打開剛文件,然后雙擊View圖標,對這個空視圖進行編輯。
4、添加各視圖元件
根據剛才的設計,向空視圖中添加元件,打開Tools-->Library,將呈現很多視圖元件,根據需要進行添加。
5、設置各視圖元件的屬性
選擇要設置的元件,然后打開Tools-->Attributes Inspector,進行屬性的設置。
6、將所需元件連接到輸出口
根據項目要求,將視圖中的個元件連接到Xcode定義的輸出口(Outlets)對應的變量中。按住Control鍵并從文檔窗口中的File's Owner圖標拖拽到對應的元件圖標上,并選擇相對應的變量。
7、連接到操作
在這個項目中,只有一個操作,那就是有觸摸按鈕產生的一個操作事件。因為之前有在有文件中有聲明一個createStory方法,選擇該按鈕元件,并打開Tools-->Connections Inspector,將事件Touch Up Inside旁邊的圓圈拖拽到Interface Builder文檔中的File's Owner圖標中,提示選擇方法時選擇createStory。在設置個元件屬性的時候,也可能用到的一個事件是Did End On Exit,連接操作的方法同本例。
8、實現視圖控制器邏輯
為了完成該項目,還需編寫實現代碼,實現代碼將編寫在*ViewController.m中,如本例需添加下列代碼:
- -(IBAction) createStory: (id) sender {
- theStory.text = [theTemplate.text
- stringByReplacingOccurrencesOfString:@"<place>"
- withString:thePlace.text];
- theStory.text = [theStory.text
- stringByReplacingOccurrencesOfString:@"<verb>"
- withString:theVerb.text];
- theStory.text = [theStory.text
- stringByReplacingOccurrencesOfString:@"<number>"
- withString:theNumber.text];
- }
9、釋放對象
在應用程序中使用完對象后,總是應釋放它以釋放內存,這是一種良好的編程習慣,也是處于一種安全性的考慮,可以盡量減少內存泄漏!下列是本例中,釋放對象的代碼:
- - (void)dealloc{
- [thePlace release];
- [theVerb release];
- [theNumber release];
- [theStory release];
- [theTemplate release];
- [generateStory release];
- [super dealloc];
- }
小結:iOS中Xcode和Interface Builder聯合應用 實例操作的內容介紹完了,希望本文對你有所幫助!!!