[英]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.