如何将 UIImageViews 添加到受限于视图的 centerXAnchor 的 UIStackView?

How to add UIImageViews to a UIStackView that is constrained to the centerXAnchor of a view?

我正在尝试通过 UIImageViews 将配置文件图标添加到 UIStackView,以使图标在视图中居中。我将如何将固定框架的 UIImageViews 添加到 UIStackView 并根据 UIStackView 中不同数量的 UIImageViews 使 UIStackView 在主视图中居中?

let memberIcons: UIStackView = {
    let iconView = UIStackView()
    iconView.translatesAutoresizingMaskIntoConstraints = false
    iconView.axis = .horizontal
    iconView.spacing = 5
    iconView.distribution = .equalSpacing
    iconView.alignment = .center
    return iconView
}()

for member in story!.members {
            let circle = UIImageView()
            circle.frame = CGRect(x: 0, y: 0, width: 36, height: 36)
            circle.translatesAutoresizingMaskIntoConstraints = false
            circle.layer.cornerRadius = CGFloat(circle.frame.width / 2)
            circle.image = member.profilePicture
            circle.contentMode = .scaleAspectFill
            circle.clipsToBounds = true
            memberIcons.addArrangedSubview(circle)
        }

因为您设置了 memberIcons.distribution = .equalSpace,堆栈视图将询问其子视图的固有大小。当被询问时,UIImage(即 circle)将计算其固有大小为 "image pixel size / scale",这不是您想要的——您希望图像具有固定大小(36 x 36 ).

circle 上使用自动布局:

override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(memberIcons)
    memberIcons.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    memberIcons.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

    // Limit the stack view's width to no more than 75% of the superview's width
    // Adjust as needed
    memberIcons.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, multiplier: 0.75).isActive = true

    let width: CGFloat = 36.0
    for member in story!.members {
        // We don't care about the frame here as we're gonna use auto layout
        let circle = UIImageView(frame: .zero)
        circle.translatesAutoresizingMaskIntoConstraints = false
        circle.layer.cornerRadius = width / 2
        circle.image = member.profilePicture
        circle.contentMode = .scaleAspectFill
        circle.clipsToBounds = true
        circle.layer.borderWidth = 1
        circle.layer.borderColor = UIColor.lightGray.cgColor

        memberIcons.addArrangedSubview(circle)
        circle.widthAnchor.constraint(equalToConstant: width).isActive = true
        circle.heightAnchor.constraint(equalToConstant: width).isActive = true
    }
}

结果:

因为我们限制了 UIStackView 的宽度,所以在控制台上出现一堆自动布局错误之前,您可以添加最大数量的个人资料图像(在本例中为 7 个)。您可以将 Stack View 包含在 Scroll View 中或使用 Collection View 进行类似矩阵的显示。