swift - 如何使用 swiftUI 在 View 主体内使用变量?

标签 swift swiftui swiftui-list swiftui-navigationlink

我正在尝试使用一个变量并在 swiftui 的 foreach 中进行修改。

下面是我正在使用的代码。请让我知道如何修改 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)
                    }
                }
            }
        }
    }
}

}

以下是我收到的错误消息:
'Int' is not convertible to 'CGFloat?'

但是这个错误信息对我来说看起来不正确。我得到这个错误是因为我试图在 foreach 中修改 chatmember。

谢谢

最佳答案

您不能修改 chatmember在您的 body 函数中,它应该在 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

关于swift - 如何使用 swiftUI 在 View 主体内使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60250140/

相关文章:

swiftui - 读取和格式化日期时遇到问题

google-cloud-firestore - SwiftUI 列表会闪烁我的数据,然后使用 ObservableObject 显示一个空列表以获取 Firestore 数据

ios - swift |将 nil 赋给字符串

swift - Swift 中最喜欢的 TableView

swift - 滑动动画以删除 UICollectionView 中的 Cell - Swift 2.0

swift - 调用中参数 'item' 缺少参数

ios - UIPageViewController 滑动忽略 SwiftUI 的 navigationBarHidden(true)

ios - 动态TableView链接到文本

swiftui - 在 SwiftUI Mac 应用程序列表中删除右键单击行的轮廓

ios - 列表中的奇怪按钮行为(SwiftUI)