在 SwiftUI 中使用按钮添加形状

时间:2021-05-28 07:25:57

标签: swift button swiftui swift-playground hstack

我刚刚开始使用 SwiftUI,所以请原谅我的一些愚蠢的错误。我正在尝试制作一些可以在按下按钮时添加形状并在再次按下时将其移除的东西。

它只用一个按钮就能很好地工作,但当我用两个按钮尝试时开始表现得很奇怪。添加的形状相对于彼此移动它们的位置。我尝试使用 CGPointCGFloat 来定位它们,但没有奏效。

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)
       }
     }
   }
 }

0 个答案:

没有答案