'Conditional property in SwiftUI
How can I add an additional property based on a condition?
With my code below I get the error:
Cannot assign value of type 'some View' (result of 'Self.overlay(_:alignment:)') to type 'some View' (result of 'Self.onTapGesture(count:perform:)')
import SwiftUI
struct ConditionalProperty: View {
@State var overlay: Bool
var body: some View {
var view = Image(systemName: "photo")
.resizable()
.onTapGesture(count: 2, perform: self.tap)
if self.overlay {
view = view.overlay(Circle().foregroundColor(Color.red))
}
return view
}
func tap() {
// ...
}
}
Solution 1:[1]
Thanks to this post I found an option with a very simple interface:
Text("Hello")
.if(shouldBeRed) { $0.foregroundColor(.red) }
Enabled by this extension:
extension View {
@ViewBuilder
func `if`<Transform: View>(_ condition: Bool, transform: (Self) -> Transform) -> some View {
if condition { transform(self) }
else { self }
}
}
Here is a great blog post with additional tips for conditional modifiers: https://fivestars.blog/swiftui/conditional-modifiers.html
Warning: Conditional view modifiers come with some caveats, and you may want to reconsider using the code above after reading this: https://www.objc.io/blog/2021/08/24/conditional-view-modifiers/
Personally I would choose to use this approach in answer to OP in order to avoid the potential issues mentioned in that article:
var body: some View {
Image(systemName: "photo")
.resizable()
.onTapGesture(count: 2, perform: self.tap)
.overlay(self.overlay ? Circle().foregroundColor(Color.red) : nil)
}
Solution 2:[2]
In SwiftUI terminology, you're not adding a property. You're adding a modifier.
The problem here is that, in SwiftUI, every modifier returns a type that depends on what it's modifying.
var view = Image(systemName: "photo")
.resizable()
.onTapGesture(count: 2, perform: self.tap)
// view has some deduced type like GestureModifier<SizeModifier<Image>>
if self.overlay {
let newView = view.overlay(Circle().foregroundColor(Color.red))
// newView has a different type than view, something like
// OverlayModifier<GestureModifier<SizeModifier<Image>>>
}
Since newView
has a different type than view
, you can't just assign view = newView
.
One way to solve this is to always use the overlay
modifier, but to make the overlay transparent when you don't want it visible:
var body: some View {
return Image(systemName: "photo")
.resizable()
.onTapGesture(count: 2, perform: self.tap)
.overlay(Circle().foregroundColor(overlay ? .red : .clear))
}
Another way to handle it is to use the type eraser AnyView
:
var body: some View {
let view = Image(systemName: "photo")
.resizable()
.onTapGesture(count: 2, perform: self.tap)
if overlay {
return AnyView(view.overlay(Circle().foregroundColor(.red)))
} else {
return AnyView(view)
}
}
The recommendations I have seen from Apple engineers are to avoid using AnyView
because is less efficient than using fully typed views. For example, this tweet and this tweet.
Solution 3:[3]
Rob Mayoff already explained pretty well why this behavior appears and proposes two solutions (Transparant overlays or using AnyView
). A third more elegant way is to use _ConditionalContent.
A simple way to create _ConditionalContent
is by writing if
else
statements inside a group or stack. Here is an example using a group:
import SwiftUI
struct ConditionalProperty: View {
@State var overlay: Bool
var body: some View {
Group {
if overlay {
base.overlay(Circle().foregroundColor(Color.red))
} else {
base
}
}
}
var base: some View {
Image("photo")
.resizable()
.onTapGesture(count: 2, perform: self.tap)
}
func tap() {
// ...
}
}
Solution 4:[4]
Here's an answer similar to what Kiran Jasvanee posted, but simplified:
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.modifier(ConditionalModifier(isBold: true))
}
}
struct ConditionalModifier: ViewModifier {
var isBold: Bool
func body(content: Content) -> some View {
Group {
if self.isBold {
content.font(.custom("HelveticaNeue-Bold", size: 14))
}
else{
content.font(.custom("HelveticaNeue", size: 14))
}
}
}
}
The difference is that there's no need to add this extension:
extension View {
func conditionalView(_ value: Bool) -> some View {
self.modifier(ConditionalModifier(isBold: value))
}
}
In the ConditionalModifier
struct, you could also eliminate the Group view and instead use the @ViewBuilder
decorator, like so:
struct ConditionalModifier: ViewModifier {
var isBold: Bool
@ViewBuilder
func body(content: Content) -> some View {
// Group {
if self.isBold {
content.font(.custom("HelveticaNeue-Bold", size: 14))
}
else{
content.font(.custom("HelveticaNeue", size: 14))
}
// }
}
}
You must either use a Group view (or some other parent view) or the @ViewBuilder
decorator if you want to conditionally display views.
Here's another example in which the the text of a button can be toggled between bold and not bold:
struct ContentView: View {
@State private var makeBold = false
var body: some View {
Button(action: {
self.makeBold.toggle()
}, label: {
Text("Tap me to Toggle Bold")
.modifier(ConditionalModifier(isBold: makeBold))
})
}
}
struct ConditionalModifier: ViewModifier {
var isBold: Bool
func body(content: Content) -> some View {
Group {
if self.isBold {
content.font(.custom("HelveticaNeue-Bold", size: 14))
}
else{
content.font(.custom("HelveticaNeue", size: 14))
}
}
}
}
Solution 5:[5]
Use conditional modifiers including if - else
expressions only if you have absolutely no choice.
The huge disadvantage of conditional modifiers is they create new views which can cause unexpected behavior for example they will break animations.
Almost all modifiers accept a nil
value for no change so if possible use always something like
@State var overlay: Bool
var body: some View {
Image(systemName: "photo")
.resizable()
.overlay(overlay ? Circle().foregroundColor(Color.red) : nil)
}
Solution 6:[6]
I think the Preferred way to implement Conditional Properties
is below. It works well if you have Animations applied.
I tried a few other ways, but it affects the animation I've applied.
You can add your condition in place of false I've kept .conditionalView(false
).
Below, You can switch to true
to check the 'Hello, World!' will be shown BOLD.
struct ContentView: View {
var body: some View {
Text("Hello, World!")
.conditionalView(false)
// or use:
// .modifier(ConditionalModifier(isBold: false))
}
}
extension View {
func conditionalView(_ value: Bool) -> some View {
self.modifier(ConditionalModifier(isBold: value))
}
}
struct ConditionalModifier: ViewModifier {
var isBold: Bool
func body(content: Content) -> some View {
Group {
if self.isBold {
content.font(.custom("HelveticaNeue-Bold", size: 14))
}else{
content.font(.custom("HelveticaNeue", size: 14))
}
}
}
}
Solution 7:[7]
As easy as this
import SwiftUI
struct SomeView: View {
let value: Double
let maxValue: Double
private let lineWidth: CGFloat = 1
var body: some View {
Circle()
.strokeBorder(Color.yellow, lineWidth: lineWidth)
.overlay(optionalOverlay)
}
private var progressEnd: CGFloat {
CGFloat(value) / CGFloat(maxValue)
}
private var showProgress: Bool {
value != maxValue
}
@ViewBuilder private var optionalOverlay: some View {
if showProgress {
Circle()
.inset(by: lineWidth / 2)
.trim(from: 0, to: progressEnd)
.stroke(Color.blue, lineWidth: lineWidth)
.rotationEffect(.init(degrees: 90))
}
}
}
struct SomeView_Previews: PreviewProvider {
static var previews: some View {
Group {
SomeView(value: 40, maxValue: 100)
SomeView(value: 100, maxValue: 100)
}
.previewLayout(.fixed(width: 100, height: 100))
}
}
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 | |
Solution 2 | rob mayoff |
Solution 3 | aheze |
Solution 4 | Peter Schorn |
Solution 5 | vadian |
Solution 6 | Peter Schorn |
Solution 7 | NeverwinterMoon |