StackView 对齐问题

issue with StackView Alignment

我想用不同的对齐方式对齐 3 个堆栈

1-Image 0-0 两边如下图

2- 用户信息 + 文字 10-10 形成双边

当我将它们堆叠在一起时出现的问题我只能将它们全部设置为 0 到所有边距,每堆叠没有堆叠。

在我的项目中,所有内容都卡在左侧我想要的图像 space 在用户 + 文本堆栈中,从两个边距开始! 如何解决这个问题,使其看起来像下图一样?

因为我真的很喜欢UIStackViews,所以我把你的问题作为实验的理由。您可以将以下内容粘贴到 Xcode 7 游乐场:

import UIKit
import XCPlayground

let hostView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
hostView.backgroundColor = .whiteColor()
XCPlaygroundPage.currentPage.liveView = hostView

let headerLabel = UILabel()
headerLabel.translatesAutoresizingMaskIntoConstraints = false
headerLabel.numberOfLines = 0
headerLabel.text = "This is an info text shown on top of the image. The info text should inform the reader about the topic."

let topStackView = UIStackView(arrangedSubviews: [headerLabel])

let image = UIImage(named: "header.jpg")
let imageView = UIImageView(image: image)
imageView.backgroundColor = .yellowColor()
imageView.contentMode = .ScaleAspectFit

let bottomLabel = UILabel()
bottomLabel.translatesAutoresizingMaskIntoConstraints = false
bottomLabel.numberOfLines = 0
bottomLabel.text = "This is the story text. It is interessting and shows a lot insight to the topic. The reader should be eager to read it and at the end he/she would be able to share with friends and family."

let bottomStackView = UIStackView(arrangedSubviews: [bottomLabel])

let stackView = UIStackView(arrangedSubviews: [topStackView, imageView, bottomStackView])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .Vertical
stackView.spacing = 10

hostView.addSubview(stackView)

let views = ["stackView": stackView]
var layoutConstraints: [NSLayoutConstraint] = []
layoutConstraints += NSLayoutConstraint.constraintsWithVisualFormat("|[stackView]|", options: [], metrics: nil, views: views)
layoutConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|[stackView]", options: [], metrics: nil, views: views)
layoutConstraints.append(headerLabel.leadingAnchor.constraintEqualToAnchor(topStackView.leadingAnchor, constant: 10))
layoutConstraints.append(headerLabel.trailingAnchor.constraintEqualToAnchor(topStackView.trailingAnchor, constant: 10))

let imageSize = image!.size
let imageHeight = hostView.frame.size.width * imageSize.height / imageSize.width
layoutConstraints.append(imageView.heightAnchor.constraintEqualToConstant(imageHeight))

layoutConstraints.append(bottomLabel.leadingAnchor.constraintEqualToAnchor(bottomStackView.leadingAnchor, constant: 10))
layoutConstraints.append(bottomLabel.trailingAnchor.constraintEqualToAnchor(bottomStackView.trailingAnchor, constant: 10))

NSLayoutConstraint.activateConstraints(layoutConstraints)

或者你可以看看我的 UIStackViewPlayground.

的 Story View 页面