gpt4 book ai didi

Swift - UITextField 搜索以同时向 UITableView 添加行

转载 作者:行者123 更新时间:2023-11-28 14:22:03 25 4
gpt4 key购买 nike

我有这个搜索功能:

func searchFor(_ text: String) {
for path in allPoemsPaths {
for poem in Helper.getPoems(filePath: path) {
if poem.body.applyingTransform(.stripDiacritics, reverse: false)!.contains(text) {
searchResults.append(poem)

resultsTable.beginUpdates()
resultsTable.insertRows(at: [IndexPath(row: searchResults.count-1, section: 0)], with: .automatic)
resultsTable.endUpdates()
}
}
}
}

它由 UITextField 委托(delegate)调用:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
searchTextField.resignFirstResponder()

searchResults.removeAll()
resultsTable.reloadData()

searchFor(" " + textField.text! + " ")

return true
}

此搜索通过超过十万个文本文件进行。

我想在找到搜索到的文本并能够选择它后动态/同时添加一行,即使搜索未完成也是如此。

我得到的是搜索完成后添加的行。

知道怎么做吗?

提前致谢。

更新:

getPoems 函数:

static func getPoems(filePath: String) -> [Poem] {

// Extracting author name
let array = filePath.components(separatedBy: "/").last!.components(separatedBy: "_")
let arabicName = array[2]

var poems = [Poem]()
let poemsString = try! String(contentsOfFile: filePath, encoding: .utf8)

// separate the file by '---' into array
var poemsArray = poemsString.components(separatedBy: "---")

// First item in the array is empty
poemsArray.removeFirst()

for poemItem in poemsArray {
var poem = Poem()

if let poemBody = getXmlItem("poem", from: poemItem) {
poem.body = poemBody
} else {
continue
}

// Extract title
if let indexOfSlash = poem.body.index(of: "/") {
poem.title = String(poem.body[..<indexOfSlash])
} else {
continue
}

if let i = getXmlItem("index", from: poemItem) {
poem.index = Int(i) ?? 0
}
if let n = getXmlItem("versesNumber", from: poemItem) {
poem.numberOfVerses = Int(n) ?? 0
}
poem.bahr = getXmlItem("bahr", from: poemItem) ?? " "

poem.qafiya = getXmlItem("qafiya", from: poemItem) ?? " "

poem.author = arabicName

poems.append(poem)
}

return poems
}

最佳答案

尝试像这样改变你的方法

func searchFor(_ text: String) {
DispatchQueue.global().async {
for path in self.allPoemsPaths {
for poem in Helper.getPoems(filePath: path) {
if poem.body.applyingTransform(.stripDiacritics, reverse: false)!.contains(text) {

DispatchQueue.main.async {
self.searchResults.append(poem)
self.resultsTable.beginUpdates()
self.resultsTable.insertRows(at: [IndexPath(row: self.searchResults.count-1, section: 0)], with: .automatic)
self.resultsTable.endUpdates()
}
}
}
}
}
}

关于Swift - UITextField 搜索以同时向 UITableView 添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51844356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com