【问题标题】:How to use variable inside the body of the view using swiftUI?如何使用 swiftUI 在视图主体内使用变量?
【发布时间】:2020-05-31 15:48:42
【问题描述】:

我正在尝试使用变量并在 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 中修改聊天成员。

谢谢

【问题讨论】:

标签: swift swiftui swiftui-list swiftui-navigationlink


【解决方案1】:

您不能在 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

【讨论】:

  • 你能举个例子吗?
  • 你可以定义一个函数并在你的函数中列出你的列表。为您的结构定义 init() 并在其中调用您的函数
  • 你能帮我编写示例代码吗?当我们点击单元格项目时,我想修改该值并将其传递给新视图,就像我们之前在“选择行”中所做的那样。类似于我想做的事情。请帮助我编写编码示例我是 swiftUI 的新手
  • 谢谢,我会实施并检查它。你能检查一下这个问题吗stackoverflow.com/questions/60250383/…
  • 值没有反映到我的聊天视图中。它不工作
猜你喜欢
  • 1970-01-01
  • 2020-07-21
  • 1970-01-01
  • 2021-02-05
  • 2022-12-26
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多