0

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)
       }
     }
   }
 }
  • You have to set a position. ```.position(x: 100, y: -200)``` for second RoundedRectangle – Raja Kishan May 28 '21 at 07:55
  • @RajaKishan Thanks, it works for the first part, but the shape still shifts when the first Rounded rectangle is removed. Isn't there a way to anchor the shapes to a single point and stop them from being affected by other elements in the view ? – AtharvSalokhe May 28 '21 at 15:05

0 Answers0