2012-07-05 85 views
1

我想使用NSBox * dynamicSection根據從NSPopUpButton控件中選擇的索引,用不同視圖替換框的內容。下面的方法接收NSPopUPButton作爲對象,並使用大小寫切換來動態設置該框的視圖和標題。用NSBox替換子視圖

@interface AppDelegate : NSObject <NSApplicationDelegate> { 
IBOutlet NSTextField *dynamicTitle; 
NSMutableString *title; 
NSBox *dynamicSection; 
NSView *Sect1_View; 
NSView *Sect2_View; 
NSView *Sect3a_View; 
NSView *Sect3b_View; 
NSView *Sect3c_View; 
NSView *Sect4_View; 
} 
@property (assign) IBOutlet NSWindow *window; 
@property (assign) IBOutlet NSBox *dynamicSection; 
@property (assign) IBOutlet NSPopUpButton *menuOptions; 

} 

@implementation { 

- (IBAction)menuSelected:(NSPopUpButton *)sender { 

NSInteger index = [sender indexOfSelectedItem]; 
NSLog(@"Selected button index is %ld", index); 



switch (index) { 
    case 0: 
     dynamicSection = [[NSBox alloc] init]; 
     [dynamicSection setTitle:[self returnSectionTitle:index]]; 
     [dynamicSection setContentView:Sect1_View]; 
     NSLog(@"%@",[self returnSectionTitle:index]); 
     break; 
    case 1: 
     dynamicSection = [[NSBox alloc] init]; 
     [dynamicSection setTitle:[self returnSectionTitle:index]]; 
     [dynamicSection setContentView:Sect2_View]; 
     break; 
    case 2: 
     dynamicSection = [[NSBox alloc] init]; 
     [dynamicSection setTitle:[self returnSectionTitle:index]]; 
     [dynamicSection setContentView:Sect3a_View]; 
     break; 
    case 3: 
     dynamicSection = [[NSBox alloc] init]; 
     [dynamicSection setTitle:[self returnSectionTitle:index]]; 
     [dynamicSection setContentView:Sect3b_View]; 
     break; 
    case 4: 
     dynamicSection = [[NSBox alloc] init]; 
     [dynamicSection setTitle:[self returnSectionTitle:index]]; 
     [dynamicSection setContentView:Sect3c_View]; 
     break; 
    case 5: 
     dynamicSection = [[NSBox alloc] init]; 
     [dynamicSection setTitle:[self returnSectionTitle:index]]; 
     [dynamicSection setContentView:Sect4_View]; 
     break; 

    default: 
     break; 
    } 

} 

}

據識別正確的索引,以及打印該標題到日誌,然而,它不能正確地切換選擇後的圖。有什麼建議麼?

謝謝!

回答

0

您似乎並沒有將NSBox作爲視圖的子視圖添加進來,我無法從問題中看出應該添加的位置。

其他問題:

  1. 您需要通過在您將它作爲一個子視圖,因爲視圖會保留它釋放分配NSBox,以避免內存泄漏。
  2. 大概不需要持有dynamicSection作爲班級的一個ivar。
  3. 你有太多的重複代碼:

switch之前:

dynamicSection = [[NSBox alloc] init]; 
[dynamicSection setTitle:[self returnSectionTitle:index]]; 

switch後添加視圖:

[someView addSubview:dynamicSection]; 
[dynamicSection release]; 
+0

謝謝你的建議,我有在switch語句之前和之後進行更改。我是否需要在NSBox中創建一個自定義視圖作爲子視圖? – user1505130 2012-07-05 21:11:36

+0

不,您需要將'NSBox' **添加到**視圖中。 – trojanfoe 2012-07-05 21:12:55

+0

你能提供一個例子嗎?我目前將NS​​Box放置在與AppDelegate關聯的Nib主視圖中。 – user1505130 2012-07-05 21:19:08