I am just starting out with SwiftUI so excuse me for some silly mistakes. I am trying to make something that will add a shape when the button is pressed and remove it when pressed again.
It works well with just one button but starts to act weird when I try it with two buttons. The shapes added shift their position relative to one another. I tried using CGPoint
as well as CGFloat
to position them but none worked.
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
@State private var isTapped = false
@State private var isTapped2 = false
var body: some View {
HStack {
//Button 1
Button(action: {
self.isTapped.toggle()
}) {
Text("1")
.padding()
.foregroundColor(.black)
.background(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.black, lineWidth: 3)
.frame(width: 75, height: 75)
)
}.position(CGPoint(x: 155, y: 395))
//Button 2
Button(action: {
self.isTapped2.toggle()
}) {
Text("2")
.padding()
.foregroundColor(.black)
.background(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.black, lineWidth: 3)
.frame(width: 75, height: 75)
)
}.position(CGPoint(x: 170, y: 395))
}
//Adding a rounded rectangle when button is pressed
HStack{
if isTapped {
RoundedRectangle(cornerRadius: 10, style: .continuous)
.frame(width: 50, height: 50)
.position(x: 150, y: -200)
.foregroundColor(Color.red)
}
if isTapped2 {
RoundedRectangle(cornerRadius: 10, style: .continuous)
.frame(width: 50, height: 50)
.position(x: 250, y: -200)
.foregroundColor(Color.red)
}
}
}
}