I want my swift code to space each imageview by 5 percent of the view controller width. So imageview a is the first 10 percent of the width then a 5 percent gap then another imageview with 10 percent width followed by 5 percent gap. You can see what I am looking for in the image below. Right now my code is not compiling with the error at smith += self.view.widthAnchor * 0.05. All code is below.
import UIKit
class ViewController: UIViewController {
var box1 = UIImageView();var box2 = UIImageView();var box3 = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
var smith : Double = 0
[box1,box2,box3].forEach{
view.addSubview($0)
$0.backgroundColor = .red
$0.translatesAutoresizingMaskIntoConstraints = false
$0.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: CGFloat(smith)).isActive = true
$0.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
$0.heightAnchor.constraint(equalTo: self.view.heightAnchor,multiplier: 0.1).isActive = true
$0.widthAnchor.constraint(equalTo: self.view.widthAnchor,multiplier: 0.1).isActive = true
smith += self.view.widthAnchor * 0.05
}
print(smith)
}
}
There are a number of ways to do this. Which approach to use would depend on what else you're planning on doing with your app and these image views.
One easy method is to use a UIStackView
.
Since each image view will be 10% of the width of the view, and we want the spacing between them to be 5% the width of the view:
10% + 5% + 10% + 5% + 10% == 40%
so we know the stack view should be 40% of the width of the view, with its Distribution set to Equal Spacing
.
Here is example code:
class BoxesViewController: UIViewController {
let box1 = UIImageView()
let box2 = UIImageView()
let box3 = UIImageView()
let stackView = UIStackView()
override func viewDidLoad() {
super.viewDidLoad()
// stack view properties
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .equalSpacing
stackView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(stackView)
[box1,box2,box3].forEach {
stackView.addArrangedSubview($0)
$0.backgroundColor = .red
// make the image views square (1:1 ratio ... height == width)
$0.heightAnchor.constraint(equalTo: $0.widthAnchor).isActive = true
// each image view is 10% of the width of the view
$0.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.10).isActive = true
}
// we want spacing between the image views to be 5% of teh width of the view
// so...
// 10% + 5% + 10% + 5% + 10% == 40%
stackView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.40).isActive = true
// let's constrain the stack view 20-pts from the top (respecting safe area)
stackView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20.0).isActive = true
// zero pts from leading
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0.0).isActive = true
}
}
Result:
and, if we rotate the device, we still get 10% image views and 5% spacing: