Reputation: 11
I have a heart image/system image that I want to appear by changing the opacity when you tap it two times, but I cannot figure out how to.
import SwiftUI
import PlaygroundSupport
struct ContentView: View{
var body: some View{
Image("apple")
.resizable()
.scaledToFill()
.clipShape(Circle())
.frame(width:200,height:200)
.overlay(
Image(systemName: "heart.fill")
.font(.system(size:50))
.foregroundColor(.red)
.opacity(0)
.onTapGesture(count:2){
}
)
}
}
I expected by tapping on the image two times:
Image(systemName: "heart.fill")
.font(.system(size:50))
.foregroundColor(.red)
.opacity(0)
.onTapGesture(count:2){
opacity(2)
}
it will show the heart, by I cannot change anything
Upvotes: 1
Views: 967
Reputation: 6029
Opacity's value range is 0.0(invisible) to 1.0(fully opaque). A @State property can be used to record the current state of opacity and the double-tap can be used to toggle between two opacity values. The onTapGesture was placed on the apple image as the tap gesture won't respond when placed on the heart if the heart isn't visible.:
struct ContentView: View{
@State private var isHidden = true
var body: some View{
Image("apple")
.resizable()
.scaledToFill()
.clipShape(Circle())
.frame(width:200,height:200)
.overlay(
Image(systemName: "heart.fill")
.font(.system(size:50))
.foregroundColor(.red)
.opacity(isHidden ? 0.0 : 1.0)
)
.onTapGesture(count:2){
isHidden.toggle()
}
}
}
Edit: meant to move the tapGesture not copy it.
Upvotes: 0
Reputation: 36807
In SwiftUI you generally change the state of a variable opacity
in this example, to
change the view. Try this example code to change the opacity (which is 0...1)
of the heart when you double tap on it.
struct ContentView: View {
@State var opacity = 1.0 // <-- here
var body: some View{
Image(systemName: "house") // <-- for testing
.resizable()
.scaledToFill()
.clipShape(Circle())
.frame(width:200,height:200)
.overlay(
Image(systemName: "heart.fill")
.font(.system(size:50))
.foregroundColor(.red)
.opacity(opacity) // <-- here
.onTapGesture(count: 2) {
opacity = 0.2 // <-- here
}
)
}
}
EDIT-1:
If you want to show the heart
when you double tap on the main image,
then put the onTapGesture
on that image, as shown in the example code.
In this example if you double tap on the house
again the heart
disappears.
struct ContentView: View {
@State var showHeart = false // <--- here
var body: some View{
Image(systemName: "house") // <-- for testing
.resizable()
.scaledToFill()
.clipShape(Circle())
.frame(width:200,height:200)
.onTapGesture(count: 2) {
showHeart.toggle() // <--- here
}
.overlay(
Image(systemName: "heart.fill")
.font(.system(size:50))
.foregroundColor(.red)
.opacity(showHeart ? 1.0 : 0.0) // <--- here
)
}
}
Upvotes: 0