1

我想使用 NSBox *dynamicSection 根据从中选择的索引和 NSPopUpButton 控件用不同的视图替换框的内容。下面的方法接收 NSPopUPButton 作为对象,并使用大小写开关来动态设置框的视图和标题。

@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;
  }

}

}

它正在识别正确的索引,并将标题打印到日志中,但是在选择时无法正确切换视图。有什么建议么?

谢谢!

4

1 回答 1

0

您似乎没有将其添加NSBox为视图的子视图,我无法从应该添加它的问题中看出。

其他问题:

  1. 一旦您将其添加为子视图,您需要通过释放分配的内存来避免内存泄漏NSBox,因为视图将保留它。
  2. 可能不需要将dynamicSection其作为类的 ivar。
  3. 你有太多重复的代码:

在之前执行此操作switch

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

并在之后添加视图switch

[someView addSubview:dynamicSection];
[dynamicSection release];
于 2012-07-05T20:55:37.240 回答