用 NSArray 和 NSMutableArray 填充 NSStackView

Fill NSStackView with NSArray and NSMutableArray

我有一个堆栈来填充一系列视图。

_countViewArray = [[NSArray alloc] init];
_countViewArray = @[self.a.view,self.b.view,self.c.view];
_stackView = [NSStackView stackViewWithViews:_countViewArray];

效果很好。 如果我想用可变数组替换这个数组怎么办?

我尝试将此代码用于 "dynamic" 堆栈视图,并最终将可变数组转换为简单数组但不起作用:

_mutableCountViewArray = [[NSMutableArray alloc] init];

[_mutableCountViewArray addObject:@[self.a.view]];
if (caseCondition){
   [_mutableCountViewArray addObject:@[self.b.view]];
}
[_mutableCountViewArray addObject:@[self.c.view]];

_countViewArray = [_mutableCountViewArray copy];
_stackView = [NSStackView stackViewWithViews:_countViewArray];

在控制台中,如果我打印可变数组,我有:

(
    (
    "<NSView: 0x600000121ea0>"
),
    (
    "<NSView: 0x600000120780>"
,
    (
    "<NSView: 0x6000001235a0>"
)
)

我该如何解决?

问题是您添加的是数组(包含单个视图)而不是视图...

记住,@[x] 是一个文字表达式,定义了一个包含 x

NSArray

所以一行是这样的:

[_mutableCountViewArray addObject:@[self.a.view]];

应该变成:

[_mutableCountViewArray addObject:self.a.view];

(当然,这适用于您在接下来的几行中添加的每个对象...)


此外,作为旁注:

_countViewArray = [[NSArray alloc] init];

你的第一个片段是多余的,因为你在下一行重新分配了一个值...