UIStackView 自身的 intrinsicContentSize

UIStackView's own intrinsicContentSize

我正在使用具有以下配置的 UIStackView:

let contentView = UIStackView()
contentView.distribution = .EqualSpacing
contentView.alignment = .Center
contentView.spacing = horizontalSpacing

每个元素都有自己的 intrinsicContentSize,因此 UIStackView 应该可以提供自己的 intrinsicContentSize。文档指出 spacing 用作最小间距。

示例:

view1: width=10
view2: width=15
spacing = 5
[view1(10)]-5-[view2(15)]

stackView的intrinsicContentSize.width应该是30.

相反,我得到:

▿ CGSize
 - width : -1.0
 - height : -1.0 { ... }

这告诉我无法提供 intrinsicContentSize

你们中有人知道我是否做错了什么,行为是故意的还是错误?

您创建的 UIView 的固有高度和宽度为零。尝试对底层 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;

这会起作用,因为堆栈视图现在有高度和宽度。

自 iOS 9.1 起,UIStackView 未实现 intrinsicContentSize:

import UIKit
import ObjectiveC

let stackViewMethod = class_getInstanceMethod(UIStackView.self, "intrinsicContentSize")
let viewMethod = class_getInstanceMethod(UIView.self, "intrinsicContentSize")
print(stackViewMethod == viewMethod)

输出:

true

如果你真的需要,你可以创建一个 UIStackView 的子类并自己实现它。不过,您不需要这样做。如果 UIStackView 被允许(通过对其的约束)选择自己的大小,它会根据其排列的子视图的固有内容大小(或您对其排列的子视图的大小设置的其他约束)进行选择.

改用这个:

stackView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)

如果您希望使其适合视图,您可以传递实际视图的框架和水平和垂直配件所需的优先级。例如,这将保留视图的宽度并调整高度:

stackView.systemLayoutSizeFitting(view.frame.size, withHorizontalFittingPriority: .required, verticalFittingPriority: .defaultLow)