您创建的 UIViews 的固有高度和宽度为零。尝试对底层 UIView 使用自动布局约束。
您也可以使用自动布局来调整 UIStackView 的大小,如果这样做,请不要将对齐设置为居中,而应使用填充。
例子:
@property (nonatomic, strong) UIStackView *firstStackView;
@property (nonatomic, strong) UIView *redView;
@property (nonatomic, strong) UIView *blueView;
@property (nonatomic, strong) UIView *yellowView;
@property (nonatomic, strong) UIView *greenView;
@property (nonatomic, strong) NSArray *subViews;
self.redView = [[UIView alloc] init];
self.redView.backgroundColor = [UIColor redColor];
self.blueView = [[UIView alloc] init];
self.blueView.backgroundColor = [UIColor blueColor];
self.yellowView = [[UIView alloc] init];
self.yellowView.backgroundColor = [UIColor yellowColor];
self.greenView = [[UIView alloc] init];
self.greenView.backgroundColor = [UIColor blackColor];
self.subViews = @[self.greenView,self.yellowView,self.redView,self.blueView];
self.firstStackView = [[UIStackView alloc] initWithArrangedSubviews:self.subViews];
self.firstStackView.translatesAutoresizingMaskIntoConstraints = NO;
self.firstStackView.distribution = UIStackViewDistributionFillEqually;
self.firstStackView.axis = UILayoutConstraintAxisHorizontal;
self.firstStackView.alignment = UIStackViewAlignmentFill;
[self.firstStackView.heightAnchor constraintEqualToConstant:40].active = YES;
[self.firstStackView.widthAnchor constraintEqualToConstant:500].active = YES;
这将起作用,因为 stackview 现在具有高度和宽度。