Reputation: 143
I was working on a live playground project and I created everything programmatically but I am not able to align my buttons in the stackView to centre please help me here is code for the main playground
import PlaygroundSupport
import UIKit
let vc = HomeViewController()
let navController = UINavigationController(rootViewController: vc)
navController.view.frame = CGRect(x: 0, y: 0, width: 600, height: 600)
PlaygroundPage.current.liveView = navController
here is my code for HomeVC
import UIKit
public class HomeViewController:UIViewController{
let stackView:UIStackView = {
let st = UIStackView()
st.axis = .horizontal
st.alignment = .center
st.distribution = .fillEqually
st.backgroundColor = .cyan
st.spacing = 10
st.translatesAutoresizingMaskIntoConstraints = false
return st
}()
let generateButton:UIButton = {
let btn = UIButton()
btn.setTitle("Generate Array", for: .normal)
btn.backgroundColor = .yellow
btn.translatesAutoresizingMaskIntoConstraints = false
return btn
}()
let generateButton2:UIButton = {
let btn = UIButton()
btn.setTitle("Generate 2", for: .normal)
btn.backgroundColor = .brown
btn.translatesAutoresizingMaskIntoConstraints = false
return btn
}()
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemPink
view.addSubview(stackView)
stackView.addArrangedSubview(generateButton)
stackView.addArrangedSubview(generateButton2)
stackView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
stackView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
stackView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
stackView.heightAnchor.constraint(equalToConstant: 120).isActive = true
}
}
All I want is to align the buttons in that stack view to centre ..... please help me
Upvotes: 0
Views: 85
Reputation: 4376
Your buttons are centred correctly, UINavigationBar
give you an illusion that they are not. To fix the issue, you have few options:
Hide navigation bar:
navigationController?.setNavigationBarHidden(true, animated: false)
Remove navigation bar translucency:
navigationController?.navigationBar.isTranslucent = false
Set edgesForExtendedLayout
to an empty array (Source):
edgesForExtendedLayout = []
All these actions can be performed in viewDidLoad()
function.
Upvotes: 1