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

时间:2018-07-20 21:25:56

标签: uiimageview swift4 uistackview

我试图通过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)
        }

1 个答案:

答案 0 :(得分:0)

由于设置了memberIcons.distribution = .equalSpace,所以堆栈视图将要求其子视图获得其固有大小。当系统询问时,UIImage(即circle)会将其固有尺寸计算为“图像像素尺寸/比例”,这不是您想要的-您希望图像具有固定的尺寸(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
    }
}

结果:

Apple's executives

由于我们限制了UIStackView的宽度,因此在控制台上出现一堆自动布局错误之前,可以添加最大数量的配置文件图像(在这种情况下为7)。您可以将“堆栈视图”封闭在“滚动视图”内部,也可以将“集合视图”用于类似矩阵的显示。