UIStackView 对齐问题

UIStackView alignment issue

我想达到这个要求

如果垂直堆叠有两个标签,则文本应与图像居中对齐

如果不是顶部对齐图像

如何在不编写任何代码的情况下实现这一点

  • labels vertical stackview 保留在 Horizontal stackView 中。

  • 如果您有超过 2 个标签,请将 Horizontal stackView 对齐方式更改为 top,否则保持 center

  • 你的布局结构应该像


> main stack view (Horizontal)
 > Image
 > stack view (Horizontal)
   >labels stack view (Vertical)
    > Labels

您需要控制外部(即包含图像和标签的堆栈视图的最终堆栈视图)堆栈视图的 alignment

由于您需要控制需要将哪些标签添加到标签的堆栈视图中,因此我假设您将以编程方式执行此操作。所以基本上你需要:

finalStackView.alignment = labelsStackView.arrangedSubviews.count > 2 ? .top : .center

这是一个完整的示例,它会产生以下输出:

class ViewController: UIViewController {

    let finalStackView = UIStackView()

    override func viewDidLoad() {
        super.viewDidLoad()
        let imageView = UIImageView()
        imageView.translatesAutoresizingMaskIntoConstraints = false
        imageView.heightAnchor.constraint(equalToConstant: 200).isActive = true
        imageView.widthAnchor.constraint(equalToConstant: 200).isActive = true
        imageView.image = #imageLiteral(resourceName: "taylor-swift")

        let label1 = UILabel()
        let label2 = UILabel()
        let label3 = UILabel()
        let label4 = UILabel()

        label1.translatesAutoresizingMaskIntoConstraints = false
        label2.translatesAutoresizingMaskIntoConstraints = false
        label3.translatesAutoresizingMaskIntoConstraints = false
        label4.translatesAutoresizingMaskIntoConstraints = false

        label1.text = "Hello"
        label2.text = "72 mins"
        label3.text = "Hello 3"
        label4.text = "Hello 4"

        let labelsStackView = UIStackView(arrangedSubviews: [label1, label2, label3, label4])
        labelsStackView.translatesAutoresizingMaskIntoConstraints = false
        labelsStackView.axis = .vertical
        labelsStackView.distribution = .fill
        labelsStackView.alignment = .leading

        finalStackView.addArrangedSubview(imageView)
        finalStackView.addArrangedSubview(labelsStackView)
        finalStackView.axis = .horizontal
        finalStackView.distribution = .fill
        finalStackView.alignment = labelsStackView.arrangedSubviews.count > 2 ? .top : .center

        view.addSubview(finalStackView)
        finalStackView.translatesAutoresizingMaskIntoConstraints = false
        finalStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        finalStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        finalStackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
    }


}    

输出上面的确切代码是:

将 2 个标签添加到 labelsStackView,输出为: