Prior to iOS 11, use a combination of topLayoutGuide and bottomLayoutGuide.
For iOS 11 or later, it is integrated into the SafeAreaLayoutGuide, so use that.
ExampleViewController.swift
private let greenView = UIView()
private func setupView() {
greenView.translatesAutoresizingMaskIntoConstraints = false
greenView.backgroundColor = .green
view.addSubview(greenView)
let margins = view.layoutMarginsGuide
NSLayoutConstraint.activate([
greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
greenView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
])
if #available(iOS 11, *) {
let guide = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
greenView.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0),
guide.bottomAnchor.constraintEqualToSystemSpacingBelow(greenView.bottomAnchor, multiplier: 1.0)
])
} else {
let standardSpacing: CGFloat = 8.0
NSLayoutConstraint.activate([
greenView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing),
bottomLayoutGuide.topAnchor.constraint(equalTo: greenView.bottomAnchor, constant: standardSpacing)
])
}
If you are not using AutoLayout, you can get the margin value of the safeArea part from safeAreaInsets, and if it is less than iOS11, you can get it from topLayoutGuide.length, bottomLayoutGuide.length.
iPhone X compatible ~ outside Safe Area ~ Positioning Content Relative to the Safe Area USE YOUR LOAF - Safe Area Layout Guide Stack Overflow - How do I use Safe Area Layout programmatically?
Recommended Posts