编辑解决方案是将它们添加到垂直堆栈 View ,感谢下面提供该解决方案的用户!
所以我是个新手,并设法创建了一个 UIStackView,但它没有在我的 View 中正确居中(它向左对齐,我不知道如何修复它。)
这就是我的代码的样子,如果有人可以帮助我弄清楚 a)为什么它没有跨越整个屏幕的宽度,或者 b)如何将 stackview 在屏幕上居中。
我一直在使用一种解决方法,通过将间距设置为等于剩余空间的大小来伪造居中外观,但我认为如果我可以将整个 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;
}
最佳答案
您只是想让堆栈 View 在单元格中居中吗?我不知道我是否确定你想做什么。你可以用两种不同的方式来做。 编辑: 尝试嵌套堆栈 View 以获得您想要的布局。我希望我的语法正确。
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];
水平堆栈进入垂直堆栈,使其调整到中心。
关于ios - UIStackView 没有将自身对齐到中心?对象C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42738940/