3

I want to space an unknown amount of buttons equally across the screen horizontally. I was wondering if I could create their spacing based off each other. For example will the code below work?

    let button1 = UIButton()
    let button2 = UIButton() 
    superview.addSubview(button1)
    superview.addSubview(button2)
    button1.snp_makeConstraints { (make) -> Void in
        make.height.equalTo(100)
        make.top.equalTo(50)
        make.left.equalTo(superview.snp.left)
        make.right.equalTo(button2.snp.right)
        make.width.lessThanOrEqualToSuperview()
    }

    button2.snp_makeConstraints { (make) -> Void in
       make.width.lessThanOrEqualToSuperview()
       make.height.equalTo(100)
       make.top.equalTo(50)
       make.left.equalTo(button1.snp.left)
       make.right.equalTo(superview.snp.right)
    }
KevinZ
  • 756
  • 1
  • 12
  • 26

1 Answers1

8

In this case you should really be using a UIStackView with a horizontal axis.

That said, if you want to use SnapKit, there are a variety of ways to do this. What I'd recommend is like so:

let count = 3  // or buttons.count if you have an array of buttons

button1.snp.makeConstraints { make in
    make.width.equalToSuperview().multipliedBy(1.0 / count)
    make.leading.equalToSuperview()
    make.top.equalToSuperview().offset(50) // or whatever
    make.height.equalTo(100)
}

button2.snp.makeConstraints { make in
   make.width.top.height.equalTo(button1)
   make.leading.equalTo(button1.snp.trailing)
}

button3.snp.makeConstraints { make in
   make.width.top.height.equalTo(button1)
   make.leading.equalTo(button2.snp.trailing)
   make.trailing.equalToSuperview()
}

Notice I'm using leading and trailing instead of left and right respectively. This is a good habit to get into in case you ever have to localize for a right-to-left language. Then your buttons will layout in a natural order for the user's device.

par
  • 17,361
  • 4
  • 65
  • 80