我正在尝试使用在 Textfield 中键入的新值更新数组项,但 List 未使用编辑后的值进行更新。
我的代码是:
模型:
struct WalletItem: Identifiable{
let id = UUID()
var name:String
var cardNumber:String
var type:String
var cvc:String
let pin:String
var dateOfExpiry:String
}
Run Code Online (Sandbox Code Playgroud)
模型视图:
class Wallet: ObservableObject{
@Published var wallets = [
WalletItem(name: "BSB", cardNumber: "123456789", type: "master card", cvc: "1234", pin: "1234", dateOfExpiry: "2016-06-29"),
WalletItem(name: "Alpha bank", cardNumber: "123456789", type: "master card", cvc: "1234", pin: "1234", dateOfExpiry: "2017-03-12"),
WalletItem(name: "MT?", cardNumber: "123456789", type: "master card", cvc: "1234", pin: "1234", dateOfExpiry: "2020-11-12"),
]
}
Run Code Online (Sandbox Code Playgroud)
第一个观点:
struct WalletListView: View {
// Properties
// ==========
@ObservedObject var wallet = Wallet()
@State var isNewItemSheetIsVisible = false
var body: some View {
NavigationView {
List(wallet.wallets) { walletItem in
NavigationLink(destination: EditWalletItem(walletItem: walletItem)){
Text(walletItem.name)
}
}
.navigationBarTitle("Cards", displayMode: .inline)
.navigationBarItems(
leading: Button(action: { self.isNewItemSheetIsVisible = true
}) {
HStack {
Image(systemName: "plus.circle.fill")
Text("Add item")
}
}
)
}
.sheet(isPresented: $isNewItemSheetIsVisible) {
NewWalletItem(wallet: self.wallet)
}
}
}
Run Code Online (Sandbox Code Playgroud)
和次要视图:
struct EditWalletItem: View {
@State var walletItem: WalletItem
@Environment(\.presentationMode) var presentationMode
var body: some View {
Form{
Section(header: Text("Card Name")){
TextField("", text: $walletItem.name)
}
}
.navigationBarItems(leading:
Button(action: {
self.presentationMode.wrappedValue.dismiss()
})
{
Text("Back")
}, trailing:
Button(action: {
self.presentationMode.wrappedValue.dismiss()
})
{
Text("Save")
})
}
}
Run Code Online (Sandbox Code Playgroud)
PS:如果我使用 @Binding 而不是 @State 我在第一个视图中出现错误:Initializer init(_:)requires thatBinding<String>符合StringProtocol
以下是修改后的部分(经过测试并适用于 Xcode 11.2 / iOS 13.2):
1) 确定过度绑定
struct EditWalletItem: View {
@Binding var walletItem: WalletItem
Run Code Online (Sandbox Code Playgroud)
2)通过的地方
List(Array(wallet.wallets.enumerated()), id: \.element.id) { (i, walletItem) in
NavigationLink(destination: EditWalletItem(walletItem: self.$wallet.wallets[i])){
Text(walletItem.name)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1624 次 |
| 最近记录: |