gpt4 book ai didi

ios - Swift 中 UITableView 的动态搜索功能

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

我正在尝试为我的 TableView 创建一个搜索功能,但是当我在我的文本字段中输入第二个字符时,该功能崩溃了。我可以输入第一个字符,删除它,然后输入一个新字符,它不会崩溃。

我的错误是:

fatal error: can not increment endIndex

我的代码是这样的:

func textFieldDidChange(textField: UITextField){
self.loadSearchData(textField.text)
}

func loadSearchData(searchString:String){

var arrayOfSearches: [String] = []
let index = count(searchString)

for company in self.companies{
let searchIndex = advance(company.startIndex, index)
if searchString == company.substringToIndex(searchIndex){
arrayOfSearches.append(company)
}
}
self.companiesToDisplay = arrayOfSearches
self.companiesTV.reloadData()
}

我的 companiesToDisplay 是我的 TableView 显示的数组。

我知道错误出在我的 let searchIndex = advance(company.startIndex, index) 行中,但我不知道为什么会产生错误。

如有任何关于如何解决此问题的建议,我们将不胜感激。

最佳答案

let searchIndex = advance(company.startIndex, index)

如果 index 大于字符数,则在运行时失败在字符串 company 中。你可以使用

let searchIndex = advance(company.startIndex, index, company.endIndex)

相反,它将起始索引增加 index 个位置,但不会超过字符串的末尾。

一个更简单的解决方案是使用hasPrefix:

for company in self.companies {
if company.hasPrefix(searchString) {
arrayOfSearches.append(company)
}
}

或者使用 rangeOfString,它有不区分大小写的搜索选项:

for company in self.companies {
if company.rangeOfString(searchString, options: .CaseInsensitiveSearch | .AnchoredSearch) != nil {
arrayOfSearches.append(company)
}
}

关于ios - Swift 中 UITableView 的动态搜索功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28683379/

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