Sou*_*hra 7 swift swiftui swiftui-list swiftui-navigationlink
我正在尝试使用一个变量并在 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)
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
以下是我收到的错误消息:
'Int' is not convertible to 'CGFloat?'
Run Code Online (Sandbox Code Playgroud)
但是这个错误信息对我来说看起来不正确。我得到这个错误是因为我试图在 foreach 中修改 chatmember。
谢谢
您不能chatmember在主体函数中修改,它应该在操作闭环中或在主体函数范围之外完成。
为了填充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
Run Code Online (Sandbox Code Playgroud)