I programmatically created a stackView with a UISegmentedControl and a Map with a MKMapView. I am using CGRect to size and place the frame of the stackView in the interface but when I switch the device simulator the stackView moves since it does not have any constraints. I usually use the StoryBoard to add constraints to anything but have never programmatically done it my self. I have seen other examples here in Stack Overflow but so far It doesn't help with what it is that I am trying to do. Here is my code showing how I am displaying it in the viewDidLoad(). If someone could explain how to add constraints programmatically so that the stackView covers 1/4 of the screen Y axis:547 please and thank you.
import UIKit
import MapKit
class SampleViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let paddedStackView = UIStackView(arrangedSubviews: [segmentedControl])
paddedStackView.layoutMargins = .init(top: 12, left: 12, bottom: 6, right: 12)
paddedStackView.isLayoutMarginsRelativeArrangement = true
let stackView = UIStackView(arrangedSubviews: [
paddedStackView, map
])
stackView.axis = .vertical
view.addSubview(stackView)
stackView.frame = CGRect(x: 0, y: 547, width: 390, height: 350)
}
let map = MKMapView()
let segmentedControl:UISegmentedControl = {
let sc = UISegmentedControl(items: ["Arriving", "Leaving"])
sc.selectedSegmentIndex = 0
sc.addTarget(self, action: #selector(handleSegmentControl), for: .valueChanged)
return sc
}()
@objc func handleSegmentControl(){
switch segmentedControl.selectedSegmentIndex {
case 0:
print("Entered Destination")
case 1:
print("Exited Destination")
default:
print("Error")
}
}