Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

i'm trying to using a variable and modify inside the foreach of swiftui.

below are the code i'm using. please let me know how can i modify the value inside the body of the view.

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

}

below are the error message i'm getting:

'Int' is not convertible to 'CGFloat?'

But this error message is not look correct for me. this error i'm getting because i tried to modify chatmember inside of foreach.

Thanks

like image 989
Sourav Mishra Avatar asked Feb 16 '20 15:02

Sourav Mishra


Video Answer


1 Answers

You can't modify the chatmember in your body function, it should be done in an action clouser or outside of the body function scope.

for populate your chatmember you can try this:

add .onAppear to your destination and set your chatmember

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
like image 177
Mac3n Avatar answered Oct 03 '22 04:10

Mac3n