当按下+按钮时,如何使表格视图添加新行并进入编辑模式?我正在使用基于NSCell的表视图。
向数据源添加一个新元素是可行的(它会创建一个空行,但不会进入编辑模式),但是我不确定这是否正确。
游乐场代码:
import PlaygroundSupport
import SwiftUI
struct TV: NSViewRepresentable {
@Binding var students: Array<String>
func makeNSView(context: Context) -> NSScrollView {
let sv = NSScrollView()
let tv = NSTableView()
sv.documentView = tv
tv.gridStyleMask = .solidHorizontalGridLineMask
tv.usesAlternatingRowBackgroundColors = true
tv.allowsMultipleSelection = true
let col = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "Name"))
col.title = "Name"
_ = tv.addTableColumn(col)
_ = tv.delegate = context.coordinator
tv.dataSource = context.coordinator
return sv
}
func updateNSView(_ nsView: NSScrollView, context: Context) {
context.coordinator.students = self.students
(nsView.documentView as! NSTableView).reloadData()
}
func makeCoordinator() -> Coordinator {
Coordinator(self, students: self.students)
}
class Coordinator: NSObject, NSTableViewDelegate, NSTableViewDataSource {
var parent: TV
var students: Array<String>
init(_ parent: TV, students: Array<String>) {
self.parent = parent
self.students = students
}
func numberOfRows(in tableView: NSTableView) -> Int {
return students.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
return students[row]
}
func tableView(_ tableView: NSTableView, shouldEdit tableColumn: NSTableColumn?, row: Int) -> Bool {
return true
}
}
}
struct view: View {
@State var students = ["John", "Mary", "Bob"]
@State var minusDisabled: Bool = true
var body: some View {
Group {
VStack(alignment: .leading) {
Text("Test")
TV(students: self.$students).frame(width: 400, height: 300)
HStack {
Button(action: {
self.students.append("")
}) {
Text("+")
}.buttonStyle(BorderedButtonStyle())
Button(action: {
}) {
Text("-")
}.buttonStyle(BorderedButtonStyle())
.disabled(self.minusDisabled)
}
}.fixedSize()
VStack {
ForEach(self.students, id: \.self) { student in
Text(student)
}.border(Color.black)
}
}
}
}
PlaygroundPage.current.setLiveView(view().frame(width: 500, height: 800))