Page 1 of 1

Swiftui: Wie kann man einen Wert aus dem Textfeld erhalten, der in einer Bottom -Blatt -Basis auf einem Wert im Zusammen

Posted: 02 Apr 2025, 01:39
by Anonymous
So sieht es in der App aus:

< /p>
Links wird eine einfache Liste von foreach < /code> erstellt. Wenn der Benutzer auf ein Element in dieser Liste tippen, wird BottomSheet mit einem gebetenen Wert für ausgewähltes Element angezeigt. Wie kann ich diesen Wert erhalten und NsManagedObject in Kerndaten aktualisieren, wenn Benutzer speichern? Gibt es eine einfache und einfache Möglichkeit, dies zu tun?

Code: Select all

struct SettingsView: View {
@State var isTextInputPresented = false
@State var editingTextFieldValue = ""
private var onSave: ((String) -> Void)? = nil

var body: some View {
ZStack {
ScrollView {
ForEach(users, id: \.self) { user in //users are from @FetchRequest
HStack {
TextLabel(user.name, color: theme.secondTeamColor)
.padding(EdgeInsets(vertical: 10))
Spacer()
}
.onTapGesture {
editingTextFieldValue = user.name
isTextInputPresented = true
// cannot assign onSave handler here🤷🏼‍♂️
}
}
}
BottomSheetView(title: "Edit input", isShowing: $isTextInputPresented) {
TextInputView(text: $editingTextFieldValue, onSave: onSave)
}
}
}
}

import SwiftUI

struct TextInputView: View {
@Environment(Theme.self) private var theme
@Binding var text: String
@FocusState private var focus: Bool
var onSave: ((String) -> Void)?
var body: some View {
HStack(spacing: 20) {
TextField("", text: $text, prompt: Text("Placeholder").foregroundColor(.gray))
.padding(10)
.multilineTextAlignment(.center)
.font(.system(size: 24))
.foregroundStyle(theme.backgroundColor)
.tint(theme.backgroundColor.opacity(0.4))
.focused($focus)
.cornerRadius(10)
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(theme.backgroundColor.opacity(0.5), lineWidth: 3)
)
Button {
onSave?(text)
} label: {
Image(systemName: "checkmark")
}
.font(.bold(withSize: 22))
.frame(width: 56, height: 56)
.background(theme.backgroundColor)
.foregroundStyle(theme.textColor)
.cornerRadius(10)
}
.padding(20)
.onAppear {
focus = true
}
}
}