我的 UIStackView 组件没有水平对齐

My UIStackView components aren't horizontially aligned

我在垂直视图中有一个水平堆栈视图,而水平视图中的元素没有对齐。

这是我目前尝试的方法

let subStackView = UIStackView()
    subStackView.axis = .horizontal
    subStackView.alignment = .trailing
    subStackView.distribution = .fill
    subStackView.spacing = 3
    subStackView.semanticContentAttribute = .forceRightToLeft
    subStackView.translatesAutoresizingMaskIntoConstraints = false
    
    let clockImage = UIImageView(image: #imageLiteral(resourceName: "Shape 8"))
    clockImage.contentMode = .scaleAspectFit
    
    let countdownLabel = UILabel()
    countdownLabel.formatteLabel(text: "12 س  35 د 12 ث", fontName: "Cairo-SemiBold", fontSize: 14)
    countdownLabel.textColor = UIColor(red: 0.94, green: 0.58, blue: 0.22, alpha: 1)
    subStackView.addArrangedSubview(clockImage)
    subStackView.addArrangedSubview(countdownLabel)
    
    rightStackView.addArrangedSubview(subStackView)

尝试在具有约束的视图中包装 clockImage。例如:

let clockImage = UIImageView(image: #imageLiteral(resourceName: "Shape 8"))
clockImage.contentMode = .scaleAspectFit

let view = UIView()
view.addSubview(clockImage)
NSLayoutConstraint.activate([
     clockImage.topAnchor.constraint(equalTo: view.topAnchor, constant: 0),
     clockImage.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0),
     clockImage.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0),
     clockImage.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0)
])

然后,代替 subStackView.addArrangedSubview(clockImage) 添加 subStackView.addArrangedSubview(view)

我认为您混淆了“水平”和“垂直”这两个词。水平横跨(从左到右或从右到左)。垂直是上下。

UIStackView 上使用 .axis = .horizontal 时,.alignment 属性 控制 垂直 对齐方式。

选项是:

  • .top
  • .center
  • .bottom
  • .firstBaseline
  • .lastBaseline

可能想要.center...尝试每一个选项,看看你是否能得到你想要的结果。