UIStackView 没有将自身对齐到中心?对象-c

UIStackView isn't aligning itself to center? obj-c

编辑解决方案是将它们添加到垂直堆栈视图中,感谢下面提供该解决方案的用户!

所以我很新,设法创建了一个 UIStackView,但它没有正确地在我的视图中居中(它向左对齐,我不确定如何修复它。)

这就是我的代码的样子,如果有人能帮我弄清楚 a) 为什么它没有跨越整个屏幕的宽度,或者 b) 我如何让堆栈视图在屏幕上居中。

我一直在使用变通方法通过将间距设置为等于剩余 space 的间距来伪造居中外观,但我认为如果我可以将整个 UIStackView 居中,则没有必要这样做

这段代码的大部分是一起破解的,所以我忽略了什么可能是简单的事情? idk,会继续摆弄它,但也许在我这样做的时候,一组更有经验的眼睛可以看看它,我会很感激

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(id)reuseIdentifier specifier:(id)specifier {

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier specifier:specifier];



    if (self) {
/*
     CGFloat width = [UIScreen mainScreen].bounds.size.width;
     CGFloat leftover = (width - (4 * 70)); //4 = number of buttons, 70 = width of buttons, is usually constant
     CGFloat newspacing = leftover/3; //3 is equal to total number of spacers needed
how i currently workaround the issue*/

//buttons declared here but omitted to save space

//Stack View
   UIStackView *stackView = [[UIStackView alloc] initWithFrame:self.bounds];
    [stackView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
    [stackView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    stackView.axis = UILayoutConstraintAxisHorizontal;
    stackView.distribution = UIStackViewDistributionEqualSpacing;
    stackView.alignment = UIStackViewAlignmentCenter;
    stackView.spacing = 5;//newspacing; //fills up leftover space..

 [stackView addArrangedSubview:bugbutton];
 [stackView addArrangedSubview:paypalbutton];
 [stackView addArrangedSubview:btcbutton];
 [stackView addArrangedSubview:musicbutton];

 stackView.translatesAutoresizingMaskIntoConstraints = false;

 [self addSubview:stackView];
}



return self;
}

您只是想让堆栈视图在单元格中居中吗?我不知道我是否确定你正在尝试做什么。你可以用两种不同的方式来做。 编辑: 尝试嵌套堆栈视图以获得所需的布局。我希望我的语法正确。

UIStackView *stackView = [[UIStackView alloc] initWithFrame:self.bounds];

stackView.axis = UILayoutConstraintAxisHorizontal;
stackView.distribution = UIStackViewDistributionFillProportionally;
stackView.alignment = UIStackViewAlignmentCenter;
stackView.spacing = 5;//newspacing; //fills up leftover space..

[stackView addArrangedSubview:bugbutton];
[stackView addArrangedSubview:paypalbutton];
[stackView addArrangedSubview:btcbutton];
[stackView addArrangedSubview:musicbutton];




UIStackView *verticalstackView = [[UIStackView alloc] initWithFrame:self.bounds];
verticalstackView.axis = UILayoutConstraintAxisVertical;
verticalstackView.distribution = UIStackViewAlignmentFill;
verticalstackView.alignment = UIStackViewAlignmentCenter;

 vericalstackView.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth)

[verticalstackView addArrangedSubview:stackView];
[self addSubview:verticalstackView];

水平堆叠进入垂直堆叠,使其调整到中心。