我试图找出如何在NSTableView中检测文本。有很多方法可以做到,而我已经尝试了全部而没有成功。我正在使用macOS 10.13和Swift 4,并且是Swift编码的新手。
我想检测targetInput中的文本,然后使用文本填充其他单元格。
我有以下代码: ViewController
import Cocoa
import Alamofire
class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate, NSTextFieldDelegate {
var stocks = [StockInformation]()
@IBOutlet weak var tableView: NSTableView!
@IBOutlet weak var input: NSTextField!
@IBAction func additem(_ sender: Any) {
if !input.stringValue.isEmpty {
let stock = StockInformation(symbol: input.stringValue)
stock.GetStockInformation {
let insertionIndex = IndexSet(integer: self.stocks.count)
self.stocks.append(stock)
self.tableView.insertRows(at: insertionIndex, withAnimation: .effectGap)
self.input.stringValue = ""
}
}
}
@IBOutlet weak var targetInput: NSTextFieldCell!
func textDidChange(_ notification: Notification) {
print("Its come here textDidChange")
guard (notification.object as? NSTextFieldCell) != nil else { return }
let numberOfCharatersInTextfield: Int = targetInput.accessibilityNumberOfCharacters()
print("numberOfCharatersInTextfield = \(numberOfCharatersInTextfield)")
}
override func viewDidAppear() {
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
}
func numberOfRows(in tableView: NSTableView) -> Int{
return stocks.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
return stocks[row]
}
public func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableView.RowActionEdge) -> [NSTableViewRowAction] {
print("swipe")
// left swipe
if edge == .trailing {
let deleteAction = NSTableViewRowAction(style: .destructive, title: "Delete", handler: { (rowAction, row) in
// action code
self.stocks.remove(at: row)
tableView.removeRows(at: IndexSet(integer: row), withAnimation: .effectFade)
})
deleteAction.backgroundColor = NSColor.red
return [deleteAction]
}
let archiveAction = NSTableViewRowAction(style: .regular, title: "Archive", handler: { (rowAction, row) in
// action code
})
return [archiveAction]
}
}