为什么需要删除/添加NSView后重新分配以显示它

时间:2017-10-09 03:44:08

标签: macos cocoa nsview

我发现当我将NSView(viewA aleardy添加到superView中)重新分配给另一个视图(new viewB)时,如下所示:

Method originalMethod = class_getInstanceMethod([NSArray class], @selector(objectAtIndexedSubscript:));
Method swapMethod = class_getInstanceMethod([NSArray class], @selector(objectAtIndexedSubscriptNew:));
method_exchangeImplementations(originalMethod, swapMethod);

viewB不会更新到superView,事件我尝试以下方法:

1)

viewA = [[NSView alloc] init];
viewB = [[NSView alloc] init];
[self.view addSubview viewA];
viewA = viewB;

2)  [viewA setHidden: YES]; [viewA setHidded: NO];

只有删除viewA并将其重新添加回它的超级视图才能正常工作:

[viewA setNeedLayout: YES];

有人可以帮忙解释为什么方法1)和2)无法更新viewA的矩形吗?

1 个答案:

答案 0 :(得分:1)

如果要查看视图层次结构,则必须将视图添加到视图层次结构中。 viewA = viewB;使变量viewA指向与viewB相同的视图,它不会将viewB添加到视图层次结构中。

以下是您的代码所做的事情:

viewA = [[NSView alloc] init]; // viewA points to a new view(A)
viewB = [[NSView alloc] init]; // viewB points to a new view(B)
[self.view addSubview viewA]; // view(A) is added to the view hierarchy and will be displayed
viewA = viewB; // variable viewA points to view(B)

[viewA setHidden: YES]; // hides view(B)
[viewA setHidded: NO]; // unhides view(B), but view(B) isn't visible because it isn't part of the view hierarchy

[viewA setNeedLayout: YES]; // doesn't do anything, view(B) isn't visible because it isn't part of the view hierarchy

[viewA removeFromSuperView]; // doesn't do anything, view(B) isn't in a superview
[self.view addSubview:viewA]; // view(B) is added to the view hierarchy and will be displayed

解决方案: 将视图(B)添加到视图层次结构

viewA = [[NSView alloc] init]; // viewA points to a new view(A)
viewB = [[NSView alloc] init]; // viewB points to a new view(B)
[self.view addSubview viewA]; // view(A) is added to the view hierarchy and will be displayed
[self.view addSubview viewB]; // view(B) is added to the view hierarchy and will be displayed