I´m developing a game and now I have noticed that it was not looking as I expected on iPhone X. What I need is to place a label on top right corner
, on iPhone X the label was not showing at all. So I read about Safe Area
and came up with this solution:
GameViewController:
override func viewDidLoad() {
super.viewDidLoad()
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
self.view.layoutSubviews()
}
override func viewDidLayoutSubviews() {
print("viewDidLayoutSubviews")
print(self.view.safeAreaInsets.top)
print(self.view.safeAreaInsets.bottom)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let scene = GameScene(size: view.bounds.size)
let skView = view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
scene.scaleMode = .resizeFill
skView.presentScene(scene)
}
And in my GameScene I´m doing this when the user
override func didMove(to view: SKView) {
var label = SKLabelNode()
if let safeAreaInsets = self.view?.safeAreaInsets {
var y: CGFloat = 0.0
if safeAreaInsets.top == 0.0 { iPhone SE, 6/7/8, Plus
y = self.frame.height - 10
} else { // iPhone X
y = frame.maxY - safeAreaInsets.top - 5
}
label.position = CGPoint(x: self.frame.width -100, y: y)
}
label.text = "Highscore: 0"
label.zPosition = 5
}
Two questions on this:
1:
This works, but do I really need to make the check if safeAreaInsets.top == 0.0
to detect if I need to use the safeAreaInsets
for iPhone X? Shouldn´t the safe area fbe the same either phone?
2:
To be able to get the safeAreaInsets
I need to call self.view.setNeedsLayout(), self.view.layoutIfNeeded(), self.view.layoutSubviews()
(probably not all but some of them). If I don´t use this all safeAreaInsets
is always 0.0. Why is this?