NSSearchField TextDidChange的方法是什么?

时间:2019-06-09 06:37:56

标签: swift xcode macos cocoa

macOS中的功能searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)的类似方法是什么?

得到答案:

 @IBOutlet weak var searchBar: NSSearchField!
  func controlTextDidChange(_ obj: Notification){
    let searchObject:NSSearchField? = obj.object as? NSSearchField
    if searchObject==self.searchBar{

    }
}

2 个答案:

答案 0 :(得分:1)

等效的是委托方法controlTextDidChange:

notification的对象是NSSearchfield。您必须转换类型

@IBOutlet weak var searchBar: NSSearchField!

func controlTextDidChange(_ notification : Notification){
    guard let field = notification.object as? NSSearchField, field == self.searchBar else { return }

}

答案 1 :(得分:0)

您需要添加如下图所示的controlTextDidChange方法(最后一个方法),然后添加searchFieldDidEndSearching

跟踪您何时完成搜索或搜索栏是否为空,并且在您清空后才开始编辑文本字段时会调用searchFieldDidStartSearching(_ sender: NSSearchField)


        DispatchQueue.main.async {
            self.searchTable.reloadData()
        }
    }

    func searchFieldDidStartSearching(_ sender: NSSearchField) {


    }

    func controlTextDidChange(_ obj: Notification) {
        guard let field = obj.object as? NSSearchField, field == self.searchBar else { return }
        filteredPokemonList = allPokemonList.filter({ (pokemon) -> Bool in
            return pokemon.name.lowercased().contains(field.stringValue.lowercased())
        })

        DispatchQueue.main.async {
            self.searchTable.reloadData()
        }
    }

下面是我的 Attribute Inspector 的图片,该函数具有一个基于输入的每个字母而调用的函数,用于过滤和重新加载NSTableView

enter image description here