I have a model for animals that contain animal name, image, position X and position Y. I try to use position X and position Y variable in .position modifier to drag and drop animal image in position X and position Y. the main problem is the .position modifier does not identify the CGFloat value (position X and position Y)
I try to call my position X and position Y by ForEach loop that is go throw all my animals model, create a variable for my model(animal) to access the position X and position Y value. when I try to print the animal.posx and animal.posy the printed value are 0.0 and 0.0.
This is my swift view:
@Query var OwnAnimal : [Kid_animal]
ForEach(OwnAnimal, id: \.self) { animal in
if animal.Animal_drag == true
{
Image(animal.animal_image).resizable()
.scaledToFit()
.frame(width: 80, height: 80)
.position(x: animal.posx, y: animal.posy)
}
else {
Circle()
.fill(Color.white)
.opacity(0.4)
.frame(width: 100, height: 100)
.position(x : animal.posx, y: animal.posy)
.onDrop(of: ["public.image"], isTargeted: nil) { providers, location in
guard let provider = providers.first else {
return false
}
if provider.canLoadObject(ofClass: UIImage.self) {
_ = provider.loadObject(ofClass: UIImage.self) { image, error in
if let image = image as? UIImage {
let droppedImage = Image(uiImage: image)
droppedImages[animal.animal_image] = droppedImage
}else{
withAnimation(Animation.easeInOut(duration: 0.2)) {
droppedImages[animal.animal_image] = nil
}
}
}
}
animal.Animal_drag = true
return true
}
.overlay(
droppedImages[animal.animal_image].map {
$0.resizable()
.scaledToFit()
.frame(width: 80, height: 80)
.position(x: animal.posx, y: animal.posy)
}
)
}
}
This is my model:
import SwiftData
import CoreGraphics
@Model
class Kid_animal {
var animal_name : String = ""
var animal_image : String = ""
var level : String = ""
var animal_energy : String = ""
var posx : CGFloat
var posy : CGFloat
var Animal_drag : Bool
init(animal_name: String, animal_image: String, level: String, animal_energy: String, posx: CGFloat , posy: CGFloat,Animal_drag : Bool) {
self.animal_name = animal_name
self.animal_image = animal_image
self.level = level
self.animal_energy = animal_energy
self.posx = posx
self.posy = posy
self.Animal_drag = Animal_drag
}
}
Follow the naming conventions, and for non optional properties you need the default value 0.0, for SwiftUI you would need to set the class to ObservedObject and @Published all the properties to be observed.
Try the above!