如何使用SnapKit实现此目的?

时间:2018-09-18 07:14:49

标签: ios swift snapkit

我想要的是这样的: enter image description here

这是我的代码:

    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"

它是这样的: enter image description here

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

1 个答案:

答案 0 :(得分:1)

删除您对label2 right 约束。

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

您的label2已附加到超级视图的左侧,且距离为100。因此,由于label1未设置宽度,因此它将调整大小以尊重右侧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个,顶部10个,左侧-10个。