2011-05-24 37 views
14

iOS是否允許開發人員定義一個私人IBOutlet。例如,viewController中有幾個按鈕,我想在界面構建器和代碼中都使用這些按鈕。但是我不想讓其他課程訪問這些按鈕。我可以定義一些 「私人」 IBOutlets此按鈕我們可以定義一個私人IBOutlet嗎?

示例代碼:

@interface myViewController : UIViewController< 
{ 
@private: 
    UIButton *o_Button1; 
    UIButton *o_Button2; 
} 

//Can I have these outlets as private??? 
@property (nonatomic, retain) IBOutlet UIButton *Button1; 
@property (nonatomic, retain) IBOutlet UIButton *Button2; 

@end 

========================= ======================================

剛剛得到一個解決方案。希望它能幫助你。

結合Abizern和JustSid想法在一起,我有這樣的一個解決方案。

在.h文件中

@interface myViewController : UIViewController 
    { 
    @private 
     IBOutlet UIButton *Button1; 
     IBOutlet UIButton *Button2; 
    } 

    @end 

和.m文件

@interface MyViewController() 

    @property (nonatomic, retain) UIButton *Button1; 
    @property (nonatomic, retain) UIButton *Button2; 

    @end 
    ... 
    @synthesize Button1, Button2; 

感謝您的幫助,從Abizern和JustSid

+0

我想如果你不設置爲對象的'@ property'和'@ synthesize',它不能在類外訪問... – visakh7 2011-05-25 09:37:54

+0

不工作!我的代碼:https://notepad.pw/4vmcjyr1。我正在使用故事板。當我繼承這個視圖控制器類並使用它。它從xib中更改了兩個屬性的值。 :( – 2016-11-18 10:37:42

回答

8

在一個類別在.m文件的頂部添加屬性:

@interface MyViewController() 

@property (nonatomic, retain) IBOutlet UIButton *Button1; 
@property (nonatomic, retain) IBOutlet UIButton *Button2; 

@end 

其實,這是怎麼了,你可以在.h文件爲只讀建立財產,並再次聲明它作爲一個讀寫.m文件中的屬性 - 這樣你就可以擁有私人設置器了。

+2

糾正我,如果我錯了,但不會這個給你在Interface Builder(或Xcode 4中的NIB編輯器)中發出警告,因爲它只在聲明的IBOutlets的.h文件中查找? – 2011-05-24 14:18:04

+8

有一點建議,除非你正在開發一個開源框架/類,否則不要打擾你的屬性/方法的私有性,這使得測試/重構/開發變得很困難。 – kubi 2011-05-24 14:19:59

+0

丹尼爾是對的。我無法在界面構建器中找到Button的插座。 – JunC 2011-05-25 09:54:44

4
@interface myViewController : UIViewController 
{ 
@private 
    IBOutlet UIButton *o_Button1; 
    IBOutlet UIButton *o_Button2; 
} 

@end 

這段代碼可以讓你有出口無其他人可能訪問的屬性。

+0

謝謝JustSid,這給我很大的幫助。我有結合了Abizern的解決方案。並在Abizern的答案張貼。 – JunC 2011-05-26 11:23:15

+0

不工作!:( – 2016-11-18 10:38:32

4

上面接受的答案有問題,IB將無法看到網點。

我使用的方法是創建一個名爲MyViewController-Protected.h文件,並將該類別與私營IBOutlets那裏。在你的MyViewController.m中包含-Protected.h而不是常規的。

受保護的文件看起來是這樣的:以這種方式定義

// MyViewController-Protected.h 
// Protected extensions to MyViewController 

#import "MyViewController.h" 

@interface MyViewController() 

@property (nonatomic, retain) IBOutlet UIButton *Button1; 
@property (nonatomic, retain) IBOutlet UIButton *Button2; 

@end 

IBOutlets只對類包括受保護的頭文件可見。這通常只是課程本身。

一旦類是在受保護的頭文件,Interface Builder中就能找到出口。 (對於XCode3,您必須將您的-Protected.h文件拖動到IB,在Xcode4中,它可以直接使用)。

相關問題