我有一个OSX应用程序用Objective写的。它在一个NSView中显示一些NSWindow,问题是我不能修改它的代码。原始模型层次结构如下所示:
NSWindow
|---> original NSView
|---> (...)我想按以下方式改变等级制度:
NSWindow
|---> NSStackView
|---> original NSView
| |---> (...)
|---> some additional NSView (say NSTextField)如何使用NSView同时显示原始NSView和相邻的附加NSView
我目前的方法或多或少是这样的(示例是简化的):
- (void)createFirstView {
NSTextField *label1 = [NSTextField labelWithString:@"First view."];
[_window setContentView: label1];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// I cannot modify this procedure:
[self createFirstView];
// I can modify that:
NSTextField *label2 = [NSTextField labelWithString:@"Second view."];
NSView *firstView = [_window contentView];
[firstView removeFromSuperview];
NSStackView *st = [NSStackView stackViewWithViews:@[firstView, label2]];
[_window setContentView:st];
}不幸的是,运行此代码后的NSWindow只显示“第二个视图”标签:

发布于 2018-11-27 16:39:13
[_window setContentView:st]在旧的内容视图上调用removeFromSuperview,removeFromSuperview释放该视图。[firstView removeFromSuperview]和[_window setContentView:st]都将发布firstView。
解决方案:将[firstView removeFromSuperview]替换为[_window setContentView:nil]。
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// I cannot modify this procedure:
[self createFirstView];
// I can modify that:
NSTextField *label2 = [NSTextField labelWithString:@"Second view."];
NSView *firstView = [_window contentView];
[_window setContentView:nil];
NSStackView *st = [NSStackView stackViewWithViews:@[firstView, label2]];
[_window setContentView:st];
}https://stackoverflow.com/questions/53499156
复制相似问题