簡體   English   中英

如何使用 swiftUI 在視圖主體內使用變量?

[英]How to use variable inside the body of the view using swiftUI?

我正在嘗試使用一個變量並在 swiftui 的 foreach 中進行修改。

下面是我正在使用的代碼。 請讓我知道如何修改視圖主體內的值。

struct SearchView : View {
var chatmember = ChatMember(with: JSON())

var body: some View{
    VStack(spacing: 10){
        VStack{
            prefView()
                .padding(.bottom, 30)
            Text("Tap to start making friend")
        }
        ScrollView(.horizontal, content: {
            HStack(spacing: 10) {
                ForEach(userDataList) { user in
                     chatmember = ChatMember(hashValue: 0, email: "", fullName: "", online: "", userId: user.userId, userImage: "", deviceToken: "", deviceType: .iOS, deviceId: "")
                    NavigationLink(destination: ChatView(chatMember: self.chatmember)){
                        SearchUser()
                    }
                }
            }
            .padding(.leading, 10)
        })
            .frame(width: 300, height: 400)

        Spacer()
    }
    .navigationBarTitle("Profile",displayMode: .inline)
    .onAppear {
        self.userList()
    }
}


@State var userDataList = [UserModel]()
func userList() {
    databaseReference.child(DatabaseNode.Users.root.rawValue).observe(.value) { (snapShot) in
        if snapShot.exists(){

            if let friendsDictionary = snapShot.value{

                for each in friendsDictionary as! [String : AnyObject]{
                    print(each)
                    if let user = each.value as? [String : Any]{
                        let data = UserModel(userId: JSON(user["userId"] ?? "").stringValue, name: JSON(user["name"] ?? "").stringValue)
                        print(data)
                        self.userDataList.append(data)
                    }
                }
            }
        }
    }
}

}

以下是我收到的錯誤消息:

'Int' is not convertible to 'CGFloat?'

但是這個錯誤信息對我來說看起來不正確。 我得到這個錯誤是因為我試圖在 foreach 中修改 chatmember。

謝謝

您不能在 body 函數中修改chatmember ,它應該在 action clouser 中或在 body 函數范圍之外完成。

要填充您的chatmember您可以嘗試以下操作:

.onAppear添加到您的目的地並設置您的聊天成員

NavigationLink(destination: ChatView(chatMember: self.chatmember).onAppear {
                     chatmember = ChatMember(hashValue: 0, email: "", fullName: "", online: "", userId: user.userId, userImage: "", deviceToken: "", deviceType: .iOS, deviceId: "")
                    }){
                        SearchUser()

don't forget to set your `chatmember` to @State

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM