Я построил на открытом воздухе , который используется в большей форме для ввода местоположения, температуры и влажности. Расположение будет выбран во втором просмотре местоположения , который появляется как лист. Нажав кнопку SELECT Во второй раз (или больше) лист остается открытым, как и ожидалось. />
import SwiftUI
import CoreLocation
struct OutdoorSection: View {
@Binding var locationName: String?
@Binding var temperature: Double
@Binding var relativeHumidity: Double
let onLocationChanged: (CLLocationCoordinate2D?) -> Void
@State private var showPickerSheet: Bool = false
var body: some View {
Section(header: Label("Outdoor", systemImage: "cloud.sun.fill")) {
VStack {
HStack {
Label(locationName ?? "", systemImage: "mappin.and.ellipse")
Spacer()
Button("Select") {
showPickerSheet = true
}
.buttonStyle(.borderless)
}
TemperatureHumidityInputs(temp: $temperature, rh: $relativeHumidity)
}
}
.sheet(isPresented: $showPickerSheet) {
LocationPicker{ name, coordinate in
showPickerSheet = false
locationName = name
onLocationChanged(coordinate)
}
}
}
}
#Preview("Form (buggy)") {
Form {
OutdoorSection(
locationName: .constant("Berlin"),
temperature: .constant(20.0),
relativeHumidity: .constant(50.0),
onLocationChanged: { _ in }
)
}
}
#Preview("No Form") {
OutdoorSection(
locationName: .constant("Berlin"),
temperature: .constant(20.0),
relativeHumidity: .constant(50.0),
onLocationChanged: { _ in }
)
}
< /code>
import SwiftUI
import MapKit
import CoreLocation
struct LocationPicker: View {
@Environment(\.dismiss) private var dismiss
@State var vm = LocationPickerViewModel()
/// callback: (placeName, coordinate) or (nil, nil) on reset
let onSelect: (String?, CLLocationCoordinate2D?) -> Void
var body: some View {
NavigationView {
VStack {
// Input + user-location button
HStack {
TextField("Enter address…", text: $vm.query)
.textFieldStyle(.roundedBorder)
Button {
vm.requestCurrentLocation()
} label: {
Image(systemName: "location")
.font(.title2)
}
.disabled(vm.isRequestingLocation)
.help("Use current location")
}
.padding()
// Show any location-error
if let err = vm.locationError {
Text(err)
.foregroundColor(.red)
.font(.caption)
}
// Autocomplete list
List(vm.suggestions, id: \.self) { suggestion in
VStack(alignment: .leading) {
Text(suggestion.title)
.font(.headline)
Text(suggestion.subtitle)
.font(.subheadline)
.foregroundColor(.secondary)
}
.contentShape(Rectangle())
.onTapGesture {
vm.search(suggestion) { name, coord in
onSelect(name, coord)
}
}
}
.listStyle(.plain)
}
.navigationTitle("Pick a Location")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
// Close without callback
ToolbarItem(placement: .navigationBarLeading) {
Button("Close") { dismiss() }
}
// Reset means “nil location”
ToolbarItem(placement: .navigationBarTrailing) {
Button("Reset") {
onSelect(nil, nil)
}
}
}
}
}
}
#Preview {
ZStack{
}
.sheet(isPresented: .constant(true)){
LocationPicker { name, coord in
print("Selected Location: \(name ?? "Unknown"), Coordinates: \(coord?.latitude ?? 0), \(coord?.longitude ?? 0)")
}
}
}
< /code>
I chatted already with GPT and got a recommendation to move showPickerSheet
Outside Outdoorsection , чтобы избежать его сброса при повторном рендере. Я попробовал это, используя привязку, безуспешно. И я думаю, что переменная принадлежит открыту>
Я построил на открытом воздухе , который используется в большей форме для ввода местоположения, температуры и влажности. Расположение будет выбран во втором просмотре местоположения , который появляется как лист. Нажав кнопку SELECT Во второй раз (или больше) лист остается открытым, как и ожидалось. /> [code]import SwiftUI import CoreLocation
struct OutdoorSection: View { @Binding var locationName: String? @Binding var temperature: Double @Binding var relativeHumidity: Double let onLocationChanged: (CLLocationCoordinate2D?) -> Void @State private var showPickerSheet: Bool = false
// Show any location-error if let err = vm.locationError { Text(err) .foregroundColor(.red) .font(.caption) }
// Autocomplete list List(vm.suggestions, id: \.self) { suggestion in VStack(alignment: .leading) { Text(suggestion.title) .font(.headline) Text(suggestion.subtitle) .font(.subheadline) .foregroundColor(.secondary) } .contentShape(Rectangle()) .onTapGesture { vm.search(suggestion) { name, coord in onSelect(name, coord) } } } .listStyle(.plain) } .navigationTitle("Pick a Location") .navigationBarTitleDisplayMode(.inline) .toolbar { // Close without callback ToolbarItem(placement: .navigationBarLeading) { Button("Close") { dismiss() } } // Reset means “nil location” ToolbarItem(placement: .navigationBarTrailing) { Button("Reset") { onSelect(nil, nil) } } } } } }
#Preview { ZStack{ } .sheet(isPresented: .constant(true)){ LocationPicker { name, coord in print("Selected Location: \(name ?? "Unknown"), Coordinates: \(coord?.latitude ?? 0), \(coord?.longitude ?? 0)") } } } < /code> I chatted already with GPT and got a recommendation to move showPickerSheet[/code] Outside Outdoorsection , чтобы избежать его сброса при повторном рендере. Я попробовал это, используя привязку, безуспешно. И я думаю, что переменная принадлежит открыту>