简体   繁体   English

在 SwiftUI 中显示和编辑文本的文本字段/视图是什么?

[英]What textfield / view to show and edit text in SwiftUI?

I would like to edit an item, for example, I have an item named "Jacket", then I would like to edit with a new name "Gray Jacket"我想编辑一个项目,例如,我有一个名为“夹克”的项目,然后我想用一个新名称“灰色夹克”进行编辑

Now I'll have the list of my items, and when I press the "Jacket" item, it will go to the DetailItem and when it appears, I want that textfield / view already filled with "Jacket" text then I able to edit it.现在我将拥有我的项目列表,当我按下“夹克”项目时,它将 go 到DetailItem并且当它出现时,我希望该文本字段/视图已经填充了“夹克”文本然后我可以编辑它。 Please note I want to use real text not placeholder when the item name first shows up.请注意,当项目名称首次出现时,我想使用真实文本而不是占位符。

Does anyone know what element should I use, or if textfield how?有谁知道我应该使用什么元素,或者如果文本字段如何? Because I couldn't find how to set textfield with name when it first appears.因为我在第一次出现时找不到如何设置带有名称的文本字段。

UPDATE:更新:

Here's what I've tried, this code I took it from here .这是我尝试过的,我从这里获取的代码。 It basically took the previous text and make it a placeholder, while actually I want it to be editable.它基本上采用了以前的文本并将其作为占位符,而实际上我希望它是可编辑的。

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
    )
}
}

Here is a possible solution:这是一个可能的解决方案:

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
    }
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM