用NSBox替换子视图

时间:2012-07-05 20:45:41

标签: objective-c xcode4 nsbox

我想使用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;
  }

}

}

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

谢谢!

1 个答案:

答案 0 :(得分:0)

您似乎没有将NSBox添加为视图的子视图,我无法从问题中找出应添加的位置。

其他问题:

  1. 一旦将分配的NSBox添加为子视图,就需要释放内存泄漏,因为视图会保留它。
  2. 可能不需要将dynamicSection作为班级的ivar。
  3. 你有太多重复的代码:
  4. switch

    之前执行此操作
    dynamicSection = [[NSBox alloc] init];
    [dynamicSection setTitle:[self returnSectionTitle:index]];
    

    并在switch

    之后添加视图
    [someView addSubview:dynamicSection];
    [dynamicSection release];