I'm reviewing 100 Days of SwiftUI Day 70 - the BuckitList project and I'm geting this runtime warning along with the warning:
"Modifying state during view update, this will cause undefined behavior.".
Atached are my ContentView.swift and Location.swift files from my BuckitList project. Indentical to the code in the lecture!!
As best I can determine, it's some sort of bug in the Map View amd the MapAnnotation custom annotation in Xcode 14. I'm running Version 14.1 (14B47b).
So I'm assuming that's the issue as pointed out by NigelGee above. Just wanted to put this out here in case others are runnng into this issue. The code runs just fine, just getting these stupid purple runtime warnings!!!
My ContentView
//
// ContentView.swift
// BucketList
//
// Created by Michael Knych on 11/17/22.
//
import SwiftUI
import MapKit
import LocalAuthentication
struct ContentView: View {
@State private var mapRegion = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 50, longitude: 0), span: MKCoordinateSpan(latitudeDelta: 25, longitudeDelta: 25))
@State private var locations = [Location]()
var body: some View {
ZStack {
Map(coordinateRegion: $mapRegion, annotationItems: locations) { location in
MapAnnotation(coordinate: location.coordinate) {
VStack {
Image(systemName: "star.circle")
.resizable()
.foregroundColor(.red)
.frame(width: 44, height: 44)
.background(.white)
.clipShape(Circle())
Text(location.name)
}
}
}
.ignoresSafeArea()
Circle()
.fill(.blue)
.opacity(0.3)
.frame(width: 32, height: 32)
VStack {
Spacer()
HStack {
Spacer()
Button {
let newLocation = Location(id: UUID(), name: "New Location", description: "", latitude: mapRegion.center.latitude, longitude: mapRegion.center.longitude)
locations.append(newLocation)
} label: {
Image(systemName: "plus")
}
.padding()
.background(.black.opacity(0.75))
.foregroundColor(.white)
.font(.title)
.clipShape(Circle())
.padding(.trailing)
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
My Location.swift file:
//
// Location.swift
// BucketList
//
// Created by Michael Knych on 11/17/22.
//
import Foundation
import MapKit
struct Location: Identifiable, Codable, Equatable {
let id: UUID
var name: String
var description: String
let latitude: Double
let longitude: Double
var coordinate: CLLocationCoordinate2D {
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
// an example for documentation
static var example = Location(id: UUID(), name: "Buckinham Palace", description: "Where King Charles lives", latitude: 50.501, longitude: -0.141)
// a custom == function for the struct to only equate the unigue id property
static func ==(lhs: Location, rhs: Location) -> Bool {
lhs.id == rhs.id
}
}