Reputation: 2872
Using SwiftUI for a small all and I noticed that the font size is very small on macOS
var body: some View {
VStack {
NavigationView {
List(fetch.Novitadss) { Novitads in
VStack(alignment: .leading) {
// 3.
Text(Novitads.title)
.font(.headline)
.fontWeight(.regular)
.onTapGesture {
UIApplication.shared.open(URL(string: Novitads.link)!)
}
}
}
I would like to add a condition to change the .font(.headline) if os is macOS so I tried
#if os(iOS)
.font(.headline)
#elseif os(macOS)
.font(.title)
#endif
but I get "Unexpected platform condition (expected 'os', 'arch', or 'swift')"
Upvotes: 5
Views: 2020
Reputation: 131
Please check this article It should be like this:
#if targetEnvironment(macCatalyst)
return self.font(.largeTitle)
#elseif os(iOS)
return self.font(.system(size: 10))
#else
return self
#endif
Upvotes: 1
Reputation: 258345
You can use the following helper extension
extension Text {
func platformFont() -> Text {
#if canImport(AppKit) || targetEnvironment(macCatalyst)
return self.font(.title)
#elseif canImport(UIKit)
return self.font(.headline)
#else
return self
#endif
}
}
and usage
Text(Novitads.title)
.platformFont()
Update: Added demo. Tested with Xcode 11.4 / macOS 10.15.4
struct ContentView: View {
var body: some View {
VStack {
Text("Hello World!")
Text("Hello World!").platformFont()
}
}
}
Upvotes: 1
Reputation: 273540
From your comment, you asked why your code did not work, which I will explain in my answer.
According to the documentation, a conditional compilation block has the following syntax:
Notice that it says "statements" inside the block. .font(.headline)
is not a statement, so it is illegal to put that there. This is also evident in the formal grammar notation further down the page:
In addition, in the "Note" block just above the formal grammar:
Each statement in the body of a conditional compilation block is parsed even if it’s not compiled. However, there is an exception if the compilation condition includes a
swift()
platform condition.
This explains why your #elseif
block has the error as well.
In other words, #if
statements are not your C++ preprocessor directives :)
Therefore, to fix the problem, you must put a whole statement in those blocks. One (dumb) way to fix this would be:
#if os(iOS)
Text(Novitads.title)
.font(.headline)
.fontWeight(.regular)
.onTapGesture {
UIApplication.shared.open(URL(string: Novitads.link)!)
}
#elseif os(macOS)
Text(Novitads.title)
.font(.title)
.fontWeight(.regular)
.onTapGesture {
// UIApplication.shared.open(URL(string: Novitads.link)!)
// you would use this on macOS to open URLs, right?
NSWorkspace.shared.open(URL(string: Novitads.link)!)
}
#endif
Of course, Asperi's solution of extracting a platformFont
method is a lot better.
Upvotes: 3