我目前正在使用Xcode 10和Swift 4.2,我试图使用SearchBar搜索到我的联系人列表,除了SearchBar超出范围返回索引外,其他所有操作都已完成。这是我的代码:
setter
昨晚,我在堆栈上进行了搜索功能,除运行该应用程序时抛出的错误外,其他都很好。我该如何解决?
@IBOutlet weak var searchBar: UISearchBar!
var contactList: [CNContact]!
var inSearchMode = false
var filteredData = [CNContact]()
override func viewDidLoad() {
super.viewDidLoad()
searchBar.delegate = self
searchBar.returnKeyType = UIReturnKeyType.done
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let store = CNContactStore()
store.requestAccess(for: .contacts, completionHandler: { (success, error) in
if success {
let keys = CNContactViewController.descriptorForRequiredKeys()
let request = CNContactFetchRequest(keysToFetch: [keys])
do {
self.contactList = []
try store.enumerateContacts(with: request, usingBlock: { (contact, status) in
self.contactList.append(contact)
})
} catch {
print("Error")
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}
})
}
答案 0 :(得分:0)
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath)
let contact: CNContact!
if inSearchMode {
contact = filteredData[indexPath.row]
} else {
contact = contactList[indexPath.row]
}
cell.textLabel?.text = "\(contact.givenName) \(contact.familyName)"
return cell
}
您应该检查是否处于搜索模式或不在cellForRow中才能正确获取
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if inSearchMode {
return filteredData.count
}
if contactList != nil {
return contactList.count
}
return 0
}
当您调用reloadData()时-numberOfRows -CellForRow也会重新调用