레이아웃 constraint 를 줄 때, 너비와 높이는 디폴트로 텍스트 크기로 설정되므로 top constraint 와 leading constraint 만 설정하면 bottom, trailing constraint 는 자동으로 계산될 거라고 생각했는데 맞겠지...?
top constraint 는 segControl 의 bottom constraint 와 10pt 띄워줬고, leading constraint 는 segControl 의 leading constraint 와 같게 설정했다.
class MapViewController: UIViewController {
private var mapView: MKMapView!
override func loadView() {
super.loadView()
mapView = MKMapView()
view = mapView
...
// label for pointsOfInterestSwitch
let pointsOfInterestLabel = UILabel()
pointsOfInterestLabel.translatesAutoresizingMaskIntoConstraints = false
pointsOfInterestLabel.text = "Points of Interest"
view.addSubview(pointsOfInterestLabel)
let labelTopConstraint = pointsOfInterestLabel.topAnchor.constraint(equalTo: segmentedControl.bottomAnchor, constant: 10)
let labelLeadingConstraint = pointsOfInterestLabel.leadingAnchor.constraint(equalTo: segmentedControl.leadingAnchor)
labelTopConstraint.isActive = true
labelLeadingConstraint.isActive = true
}
}
switch 도 디폴트 크기가 정해져 있어서 top 과 leading constraint 만 설정하려고 했는데, 그렇게 했더니 label 과 중앙이 맞지 않았다. 그래서 centerY constraint 를 label 과 같게 설정해줬다.
leading constraint 의 경우 label 의 leading constraint 에 label 의 너비만큼을 더한 값으로 설정하려고 해 처음에는 pointsOfInterestLabel.frame.width + 10
을 했는데 아무런 효과가 없었다. print 문으로 확인해보니 frame 의 width 가 0 이 나오고 있었다. 구글링 해보니 frame 대신 intrinsicContentSize 프로퍼티를 사용하라는 내용이 있었다. 얘가 바로 우리가 별도로 너비와 높이를 설정하지 않아도 내부 컨텐츠의 크기에 따라 UILabel 이나 UIButton 등의 너비와 높이를 디폴트로 연산해주는 친구라고 한다!
class MapViewController: UIViewController {
private var mapView: MKMapView!
override func loadView() {
super.loadView()
mapView = MKMapView()
view = mapView
...
// pointsOfInterestSwitch
let pointsOfInterestSwitch = UISwitch()
pointsOfInterestSwitch.translatesAutoresizingMaskIntoConstraints = false
pointsOfInterestSwitch.addTarget(self, action: #selector(togglePointsOfInterest(_:)), for: .valueChanged)
pointsOfInterestSwitch.isOn.toggle()
view.addSubview(pointsOfInterestSwitch)
let switchCenterYConstraint = pointsOfInterestSwitch.centerYAnchor.constraint(equalTo: pointsOfInterestLabel.centerYAnchor)
let switchLeadingConstraint = pointsOfInterestSwitch.leadingAnchor.constraint(equalTo: pointsOfInterestLabel.leadingAnchor, constant: pointsOfInterestLabel.intrinsicContentSize.width + 10)
switchCenterYConstraint.isActive = true
switchLeadingConstraint.isActive = true
}
@objc func togglePointsOfInterest(_ pointsSwitch: UISwitch) {
mapView.pointOfInterestFilter = pointsSwitch.isOn ? .includingAll : .excludingAll
}
}