Im new to programming and I joined StackOverflow today. I hope I can ask based on the guidelines:
I’m starting SwiftUI and it seems it has many code that works only for iOS 17, take a look at this:
if #available(iOS 17.0, *) {
Text("Hello World")
.font(.title.bold())
.multilineTextAlignment(.leading)
// This modifier only works on iOS 17
.foregroundStyle(.red)
} else {
Text("Hello World")
.font(.title.bold())
.multilineTextAlignment(.leading)
.foregroundColor(.red)
}
One of the first thing I learned is to not repeat the same code but how can I apply different modifiers easily without repeating the code? some thing like this:
Text("Hello World")
.font(.title.bold())
.multilineTextAlignment(.leading)
if #available(iOS 17.0, *) {
.foregroundStyle(.red)
} else {
.foregroundColor(.red)
}
P.S: I have seen posts like this to implement a custom modifier that takes a bool as input, but it can’t take the os version in a way that the compiler understands like #available(iOS 17.0, *)
.
Update
I know we can achieve something similar for the os check like the following, but Im looking for the check for the version in the same general way:
Text("Hello World")
.font(.title.bold())
.multilineTextAlignment(.leading)
#if os(iOS)
.foregroundStyle(.red)
#else
.foregroundColor(.red)
Thanks for considering my question
2
Answers
I think there is a simpler approach to this.
Still using a view modifier. But the modifier is specially for foreground styling. So you can check your condition inside of it.
e.g.
and apply it like:
You can achieve something quite similar with a simple extension:
Now you can use it like:
Note that you can
apply
any modifier on any view you like and it is pretty general as you asked.