Search code examples
iosswiftsnapkit

How can I use SnapKit achieve this?


I want is like this: enter image description here

Here is my code:

    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"

it works like this: enter image description here

Why is it not aligned to the left? Where am I wrong?


Solution

  • Remove your right constraint for label2.

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

    Your label2 has been attached to the super view's left at a distance of 100. So because label1 has no width set, it will resize itself to respect the right constraint of label2, thereby satisfying all the constraints that you have set.

    If you cannot remove the left constraint, then you need to get the width of the label without any constraints for a text. You can get it like this. For example,

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

    Now you set this width using snapKit to the width of label1. and set the left constraint less than or equal to 100.

    Alternatively and the better approach, You could also try having a single label with attributed text. Since you know the string of the first label and the second label, you can easily format it with NSAttributedString avoiding the headache of constraints for multiple labels.

    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)
    

    Now set the anchors as 10 right, top, -10 left.