Xcode 學習之路 Interface Builder使用技巧
最近在看電驢上down下來的ipad開發視頻教程。為加深記憶,特在此做筆記。
前兩集視頻主要講的是UIAlertView(相當于windows里面的MessageBox)
在interface builder里面添加了控件之后,要想使得控件響應事件必須做如下處理:
1:在XXXViewController.h里面添加事件響應函數聲明如:
- -(IBAction)btnOnclick:(id)sender;
2:在相應的.m文件中實現這個函數
3:回到interface builder中鼠標右鍵從需要使用這個事件相應函數的控件拖拽到File's Owner上并在彈出的選項中選中步驟1中的函數名,使之關聯起來。
注意:這個視頻里面提到了一個特別的控件就是UIAlertView,因為這個控件沒有在interface builder中提供出來編輯。所以如果這個要使這個控件的事件得到相應需要在XXXViewController.h文件里面聲明類的時候使用協議(類似C++里面的抽象基類的多重繼承)。樣子如下:
- #import <UIKit/UIKit.h>
- @interface AlertViewTestViewController : UIViewController <UIAlertViewDelegate>{
- }
- @end
然后在實現文件里面實現對應的事件處理函數。對UIAlertView來說。要使用的協議是UIAlertViewDelegate,要實現的事件響應函數是 - (void)alertView:(UIAlertView* )alertView clickedButtonAtIndex:(NSInteger)buttonIndex。實際上,使用了協議之后,可以根據協議名字在幫助里面很快的找到這個協議需要實現哪些函數。
控件還有另外一個比較重要的東西就是數據綁定。在xcode里面要實現這么一個東西步驟基本和上面的類似
1:在XXXViewController.h文件里面聲明之,下面聲明了一個文本數據
- @interface OutletAndActionViewController : UIViewController {
- IBOutlet UITextField *txtName;
- }
- @property(nonatomic, retain) UITextField *txtName;
- @end
2:實現文件里面給出set和get函數。如果使用了屬性,你懂的。。。
- @synthesize txtName;
3:回到interface builder中鼠標右鍵從File's Owner中拖拽到需要綁定這個數據的控件上并在彈出的選項中選中,使之關聯起來。拖拽方向和上面相反。寫到這里。我在想IBAction和IBOutlet到底是個啥?
在頭文件中找到了他們的定義:
- #ifndef IBOutlet
- #define IBOutlet
- #endif
- #ifndef IBAction
- #define IBAction void
- #endif
幾乎啥都沒干。最后在cocoachina上找到了答案。
原帖:http://www.cocoachina.com/bbs/read.php?tid-18829.html
內容如下:
These two keywords do absolutely nothing as far as the compiler is concerned. IBOutlet gets entirely removed from the code before the compiler ever sees it. IBAction resolves to a void return type, which just means that action methods do not return a value. So, what’s going on here?
The answer is simple, really: IBOutlet and IBAction are not used by the compiler. They are used by Interface Builder. Interface Builder uses these keywords to parse out the outlets and actions available to it. Interface Builder can only see methods that are prefaced with IBAction and can only see variables or properties that are prefaced with IBOutlet. Also, the presence of these keywords tells other programmers, looking at your code in the future, that the variables and methods in question aren’t dealt with entirely in code. They’ll need to delve into the relevant nib file to see how things are hooked up and used.
敢情這兩關鍵字完全是給interface builder看的。
小結:Xcode 學習之路 Interface Builder使用技巧 的內容介紹完了希望本文對你有所幫助!