'Using SwiftUI on watchOS, how to align views to the navigation title?
I would like to align some content to the same inset the the navigation title uses.
On older watch devices, there is no inset, but on newer devices with the rounded corners, the title is inset, and for certain things I would like to align to the same inset.
The apple docs talk about this margin, but I can't figure out how to use it.
How can I modify this example to have the left edge of the Text and Button align with the Navigation Title?
var body: some View {
VStack(alignment: .leading) {
Text("Hello World")
Button("Test") {}
}
.navigationTitle("Title")
}
Solution 1:[1]
Leading padding is simply (on the VStack):
.padding(.leading, 9.5)
but you have to do it based on the watch model. Here is an example of how to determine the watch model: How to determine the Apple Watch model?
And you might want to put this in a conditional view modifier: https://stackoverflow.com/a/62962375/14351818
Solution 2:[2]
You could use the current screen width:
var screenWidth = WKInterfaceDevice.current().screenBounds.width
and apply that (minus the desired margin) as a frame width to your VStack:
VStack(alignment: .leading){
Text("Hello World")
Button("Test") {}
}
.frame(width: screenWidth - 25)
.navigationTitle("Title")
This worked fine on 45mm and 40mm, but unfortunately still not quite there on the 38mm watch, so you might want to explicitly set different paddings/frames for smaller devices.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ChrisR |
| Solution 2 | Anher |


