2012-07-05 63 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