Xcode 學(xué)習(xí)之路 Interface Builder使用技巧
最近在看電驢上down下來(lái)的ipad開發(fā)視頻教程。為加深記憶,特在此做筆記。
前兩集視頻主要講的是UIAlertView(相當(dāng)于windows里面的MessageBox)
在interface builder里面添加了控件之后,要想使得控件響應(yīng)事件必須做如下處理:
1:在XXXViewController.h里面添加事件響應(yīng)函數(shù)聲明如:
- -(IBAction)btnOnclick:(id)sender;
2:在相應(yīng)的.m文件中實(shí)現(xiàn)這個(gè)函數(shù)
3:回到interface builder中鼠標(biāo)右鍵從需要使用這個(gè)事件相應(yīng)函數(shù)的控件拖拽到File's Owner上并在彈出的選項(xiàng)中選中步驟1中的函數(shù)名,使之關(guān)聯(lián)起來(lái)。
注意:這個(gè)視頻里面提到了一個(gè)特別的控件就是UIAlertView,因?yàn)檫@個(gè)控件沒(méi)有在interface builder中提供出來(lái)編輯。所以如果這個(gè)要使這個(gè)控件的事件得到相應(yīng)需要在XXXViewController.h文件里面聲明類的時(shí)候使用協(xié)議(類似C++里面的抽象基類的多重繼承)。樣子如下:
- #import <UIKit/UIKit.h>
- @interface AlertViewTestViewController : UIViewController <UIAlertViewDelegate>{
- }
- @end
然后在實(shí)現(xiàn)文件里面實(shí)現(xiàn)對(duì)應(yīng)的事件處理函數(shù)。對(duì)UIAlertView來(lái)說(shuō)。要使用的協(xié)議是UIAlertViewDelegate,要實(shí)現(xiàn)的事件響應(yīng)函數(shù)是 - (void)alertView:(UIAlertView* )alertView clickedButtonAtIndex:(NSInteger)buttonIndex。實(shí)際上,使用了協(xié)議之后,可以根據(jù)協(xié)議名字在幫助里面很快的找到這個(gè)協(xié)議需要實(shí)現(xiàn)哪些函數(shù)。
控件還有另外一個(gè)比較重要的東西就是數(shù)據(jù)綁定。在xcode里面要實(shí)現(xiàn)這么一個(gè)東西步驟基本和上面的類似
1:在XXXViewController.h文件里面聲明之,下面聲明了一個(gè)文本數(shù)據(jù)
- @interface OutletAndActionViewController : UIViewController {
- IBOutlet UITextField *txtName;
- }
- @property(nonatomic, retain) UITextField *txtName;
- @end
2:實(shí)現(xiàn)文件里面給出set和get函數(shù)。如果使用了屬性,你懂的。。。
- @synthesize txtName;
3:回到interface builder中鼠標(biāo)右鍵從File's Owner中拖拽到需要綁定這個(gè)數(shù)據(jù)的控件上并在彈出的選項(xiàng)中選中,使之關(guān)聯(lián)起來(lái)。拖拽方向和上面相反。寫到這里。我在想IBAction和IBOutlet到底是個(gè)啥?
在頭文件中找到了他們的定義:
- #ifndef IBOutlet
- #define IBOutlet
- #endif
- #ifndef IBAction
- #define IBAction void
- #endif
幾乎啥都沒(méi)干。最后在cocoachina上找到了答案。
原帖:http://www.cocoachina.com/bbs/read.php?tid-18829.html
內(nèi)容如下:
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.
敢情這兩關(guān)鍵字完全是給interface builder看的。
小結(jié):Xcode 學(xué)習(xí)之路 Interface Builder使用技巧 的內(nèi)容介紹完了希望本文對(duì)你有所幫助!