我想编辑一个项目,例如,我有一个名为"夹克";,那么我想用一个新名称"来编辑;灰色夹克";
现在我将有我的项目列表,当我按下";夹克";项目,它将转到DetailItem
,当它出现时,我希望该文本字段/视图已经填充了";夹克";文本,然后我可以编辑它。请注意,当项目名称第一次出现时,我想使用真实文本而不是占位符。
有人知道我应该使用什么元素吗?或者如果是textfield,该如何使用?因为当文本字段第一次出现时,我找不到如何设置它的名称。
更新:
这是我尝试过的,这个代码是我从这里获得的。它基本上采用了以前的文本并使其成为占位符,而实际上我希望它是可编辑的。
struct CustomTextField: View {
var placeholder: Text
@Binding var text: String
var editingChanged: (Bool)->() = { _ in }
var commit: ()->() = { }
var body: some View {
ZStack(alignment: .leading) {
if text.isEmpty { placeholder }
TextField("", text: $text, onEditingChanged: editingChanged, onCommit: commit)
}
}
}
struct UsageCustomTxtField: View {
@State var text = ""
var body: some View {
CustomTextField(
placeholder: Text("placeholder").foregroundColor(.black),
text: $text
)
}
}
这里有一个可能的解决方案:
import SwiftUI
struct ContentView: View {
@ObservedObject var myItems: ItemViewModel = ItemViewModel()
@State var myNewName: String = "" // Will set the new name
var body: some View {
VStack {
TextField(self.myItems.myList[0].name, // when it appears, I want that textfield / view already filled with "Jacket" text
text: self.$myNewName,
onCommit: {
self.myItems.changeNameOfListItemTo(newName: self.myNewName, index: 0) I would like to edit with a new name "Gray Jacket"
self.myNewName = "" //empty the textfield again so name from item itself will be displayed
})
}
}
}
struct Item { // I have an item named "Jacket"
var name: String
init(name: String) {
self.name = name
}
}
class ItemViewModel: ObservableObject {
@Published var myList: Array<Item> = [Item(name: "Jacket")] //your item list
func changeNameOfListItemTo(newName: String, index: Int) { //function to change the name of an item
self.myList[0].name = newName
}
}