首页 > 解决方案 > 将用户输入的信息传递给 View 并用它创建一个新的类似小部件的卡片

问题描述

在制作我的第一个个人财务跟踪器的过程中,但我被困住了,因为我想创建一张新卡,就像出现在“您的卡”下的卡一样,其中包含用户在按“添加新”后键入的信息。

import SwiftUI

struct CardListView: View {
    @EnvironmentObject var wallet: Wallet

@State var isPresentingAddModal = false

@State var cardType = ""
@State var cardNumber = ""
    
var headerView: some View {
    HStack {
        Text("Your cards")
            .font(.title2)
            .fontWeight(.bold)
        Spacer()
        Button("Add new") {
            self.isPresentingAddModal.toggle()
            print("Trying to add new card")}

            .font(.callout)
            .foregroundColor(Color.primaryPurple)
            .padding(.trailing)
    }
    .sheet(isPresented: $isPresentingAddModal, content: {
        
        HStack (spacing: 16) {
            Text("Card type")
            TextField("Enter your card type", text: $cardType)
        }
        
        HStack (spacing: 16) {
            Text("Card Number")
            TextField("Enter your card number", text: $cardNumber)
        }
        
        Button(action: {
            self.isPresentingAddModal.toggle()
            print("\(self.cardType)" + " " + "\(self.cardNumber)")
            
            // Code needed to be able to pass user info into the Wallet Cards...
            
        }, label: {
            Text("Add")
                .padding(.all, 16)
        })
        Spacer()
    })

    }
    
  //Creating the Cards index...

var body: some View {
    VStack {
        headerView
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 10) {
                ForEach(wallet.cards.indices, id: \.self) { index in
                    CardView(card: wallet.cards[index])
                        .onTapGesture {
                            wallet.cards.indices.forEach { index in
                                wallet.cards[index].isSelected = false
                            }
                            wallet.cards[index].isSelected.toggle()
                        }
                   }
              }
         }
    }
}
}

单击“添加新”后出现的模态是超级基本的,但我试图首先使其正常工作。

主页视图

标签: iosswiftxcodeuser-interfaceswiftui

解决方案


添加wallet.cards.append(Card.init())会在索引上创建另一张卡片,其中包含用户传递的信息。

在它的括号内init应该包含所有想要的常量/变量。

简单,但可以节省某人的时间和未来的头痛!


推荐阅读