【发布时间】:2015-06-10 11:09:34
【问题描述】:
我正在处理 Swift 中的自动完成文本字段。
我用了这个例子:
但对我来说cellForRowAtIndexPath 方法根本没有调用。我不知道我在这里犯了什么错误。
我的代码是这样的:
@IBOutlet weak var autocompleteTableView: UITableView!
@IBOutlet weak var searclLocationTextField: UITextField!
var pastUrls = ["Men", "Women", "Cats", "Dogs", "Children"]
var autocompleteUrls = [String]()
override func viewDidLoad() {
super.viewDidLoad()
autocompleteTableView.scrollEnabled = true
autocompleteTableView.hidden = true
// Do any additional setup after loading the view.
}
// 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 textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
println("banana")
autocompleteTableView.hidden = false
var substring = (searclLocationTextField.text as NSString).stringByReplacingCharactersInRange(range, withString: string)
searchAutocompleteEntriesWithSubstring(substring)
autocompleteTableView.reloadData()
return true
}
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()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return autocompleteUrls.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let autoCompleteRowIdentifier = "AutoCompleteRowIdentifier"
var cell = tableView.dequeueReusableCellWithIdentifier(autoCompleteRowIdentifier) as? UITableViewCell
if let tempo1 = cell
{
let index = indexPath.row as Int
cell!.textLabel!.text = autocompleteUrls[index]
} else
{
cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: autoCompleteRowIdentifier)
}
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell : UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
searclLocationTextField.text = selectedCell.textLabel!.text
println(searclLocationTextField.text)
}
【问题讨论】:
-
你映射了tableview委托吗?
-
您的意思是在 StoryBoard 中对吧?是的,我做到了
-
再次重新映射并尝试放置断点。
-
是的,我做到了。 “numberofRowsIn section”正在调用,但 cellforindexpath 没有调用如果你有示例代码,你可以发给我吗?
-
如果你的数组计数 > 0 那么只有 cellforrowatindexpath 会被调用,检查你的数组计数
标签: ios swift uitableview uitextfield