答案 0 :(得分:21)
试试这个
if #available(iOS 11.0, *) {
let window = UIApplication.shared.keyWindow
let bottomPadding = window?.safeAreaInsets.bottom
}
答案 1 :(得分:1)
您可以尝试将子视图(清除,隐藏或其他)固定到safeAreaLayoutGuide的底部,并计算此视图底部与viewDidLayoutSubviews
中视图控制器视图之间的差异。
class ViewController: UIViewController {
let measuringView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
measuringView.backgroundColor = .magenta
measuringView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(measuringView)
let vConstraint = measuringView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
let heightConstraint = measuringView.heightAnchor.constraint(equalToConstant: 34)
var constraints = NSLayoutConstraint.constraints(withVisualFormat: "|[measuring]|", options: [], metrics: nil, views: ["measuring": measuringView])
constraints.append(vConstraint)
constraints.append(heightConstraint)
NSLayoutConstraint.activate(constraints)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let measuringBottom = measuringView.frame.origin.y + measuringView.frame.height
let viewBottom = view.bounds.height
let distance = abs(measuringBottom - viewBottom)
print("distance is \(distance) points")
}
}
答案 2 :(得分:1)
重新迭代以前的答案。将子视图固定到UIViewController
视图的底部。然后将第二个固定到视图的view.safeAreaLayoutGuide.bottomAnchor
锚点。两个子视图都固定了父视图的top
,leading
和trailing
锚点。然后,我假设在viewDidAppear
中,您可以打印出两个子视图的frame.maxY
值之间的差异。这应该会给你带来不同。
let viewA = UIView()
let viewB = UIView()
override func viewDidLoad() {
view.addSubview(viewA)
view.addSubview(viewB)
viewA.translateAutoResizingMasksIntoConstraints = false
viewB.translateAutoResizingMasksIntoConstraints = false
if #available(iOS 11.0, *) {
NSLayoutConstraint.activate([viewA.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0),
viewA.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 0),
viewA.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: 0),
viewA.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: 0),
viewB.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0),
viewB.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 0),
viewB.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: 0),
viewB.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0)])
} else {
// Fallback on earlier versions
}
}
override func viewDidAppear() {
super.viewDidAppear()
print("Safe Distance Value is:\(viewA.frame.maxY - viewB.frame.maxY)")
}
作为其他人的参考,iPhone X模拟器上的值似乎为34