我正在尝试实现自动补全功能,但是找不到在Swift中可用的示例。下面,我打算转换Ray Wenderlich的自动完成教程和2010年的示例代码。最后,代码进行了编译,但是没有显示包含可能完成的表格,而且我没有经验来了解为什么它未被隐藏shouldChangeCharactersInRange。
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { @IBOutlet weak var textField: UITextField! let autocompleteTableView = UITableView(frame: CGRectMake(0,80,320,120), style: UITableViewStyle.Plain) var pastUrls = ["Men", "Women", "Cats", "Dogs", "Children"] var autocompleteUrls = [String]() override func viewDidLoad() { super.viewDidLoad() autocompleteTableView.delegate = self autocompleteTableView.dataSource = self autocompleteTableView.scrollEnabled = true autocompleteTableView.hidden = true } func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool { autocompleteTableView.hidden = false var substring = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string) searchAutocompleteEntriesWithSubstring(substring) return true // not sure about this - could be false } func searchAutocompleteEntriesWithSubstring(substring: String) { autocompleteUrls.removeAll(keepCapacity: false) var indexOfPastUrls = 0 for curString in pastUrls { let substringRange = curString.rangeOfString(curString) if (indexOfPastUrls == 0) { autocompleteUrls.append(curString) } indexOfPastUrls = indexOfPastUrls + 1 } autocompleteTableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return autocompleteUrls.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let autoCompleteRowIdentifier = "AutoCompleteRowIdentifier" var cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(autoCompleteRowIdentifier, forIndexPath: indexPath) as UITableViewCell let index = indexPath.row as Int cell.textLabel.text = autocompleteUrls[index] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedCell : UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)! textField.text = selectedCell.textLabel.text } }
用searchAutocompleteEntriesWithSubstring下面的内容替换您的函数内容。希望对您有帮助。
searchAutocompleteEntriesWithSubstring
func searchAutocompleteEntriesWithSubstring(substring: String) { autocompleteUrls.removeAll(keepCapacity: false) for curString in pastUrls { var myString:NSString! = curString as NSString var substringRange :NSRange! = myString.rangeOfString(substring) if (substringRange.location == 0) { autocompleteUrls.append(curString) } } autocompleteTableView.reloadData() }