我如何使用 SnapKit 实现这一目标?

How can I use SnapKit achieve this?

我想要的是这样的:

这是我的代码:

    let label1 = UILabel()
    let label2 = UILabel()
    label1.textColor = .white
    label1.backgroundColor = .red
    view.addSubview(label1)
    label1.snp.makeConstraints { (m) in
        m.left.equalToSuperview().offset(100)
        m.top.equalToSuperview().offset(100)
    }
    view.addSubview(label2)
    label2.snp.makeConstraints { (m) in
        m.left.equalTo(label1.snp.right)
        m.top.equalToSuperview().offset(100)
        m.right.equalToSuperview().offset(-100)
    }
    label1.text = "123456"
    label2.text = "789"

它是这样工作的:

为什么没有左对齐? 我哪里错了?

移除你对label2.

权利约束
label2.snp.makeConstraints { (m) in
    m.left.equalTo(label1.snp.right)
    m.top.equalToSuperview().offset(100)
    // m.right.equalToSuperview().offset(-100)
}

你的label2已经附加到超级视图的左边100。所以因为label1没有设置宽度,它会resize本身尊重 label2 的右约束,从而满足您设置的所有约束。

如果你不能去掉左边的约束,那么你需要得到没有任何文本约束的标签的宽度。你可以这样得到它。例如,

let label = UILabel()
label.text = "Blah"
let width = label.intrinsicContentSize.width

现在您使用 snapKit 将此宽度设置为 label1 的宽度。并将左约束设置为小于或等于 100。

或者更好的方法,您也可以尝试使用带有属性文本的单个标签。因为你知道第一个标签和第二个标签的字符串,你可以很容易地用NSAttributedString格式化它,避免了多个标签约束的头痛。

let string1 = NSAttributedString(string: "Your first string", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white, NSAttributedString.Key.backgroundColor: UIColor.red])
let string2 = NSAttributedString(string: "Your second string", attributes: [NSAttributedString.Key.foregroundColor: UIColor.black, NSAttributedString.Key.backgroundColor: UIColor.white])
var finalString: NSMutableAttributedString = NSMutableAttributedString()
finalString.append(string1)
finalString.append(string2)

现在将锚点设置为 10 right, top, -10 left。