2014-10-02 29 views
1

所以我正在使用一个Swift应用程序,它使用了一个自动完成的文本字段来显示UITableView,并根据正在输入的内容过滤结果。如何获得实际的数组索引值,当在UITableView中选择一行时使用过滤结果? Swift

有一个选择的集合数组,文本字段根据输入的内容进行过滤,并在表格视图中显示结果。现在我需要在选中该行时获取ACTUAL数组索引值,但是我知道如何使用该函数获取当前显示的索引值。例如,如果有2个结果,我只能得到0和1的索引,即使实际的数组可能是46和59.

有没有办法做到这一点?另外,我可以设置一个名称为字符串的数组,并为每个数组设置一个int,然后使用行选择获取int,然后查找名称?

眼下这是根据使用什么文本字段中键入的阵列来过滤代码

功能抓取的文本作为其在字段中输入

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool 
{ 
    autocompleteTableView.hidden = false 

    var substring :NSString = textField.text 
    substring = substring.stringByReplacingCharactersInRange(range, withString: String()) 


    return true 
} 

功能穿过阵列检查字符串是否在输入范围内

@IBAction func searchAutocompleteBrands() 
{ 
for i in 0..<brandNames.count 
    { 
     var substring: NSString = brandNames[i] as NSString 
     if let temp = substring.lowercaseString.rangeOfString(txtBrand.text) 
     { 
      filteredArrayResults.append(substring) 
     } 
     autocompleteTableView.reloadData() 
    } 
} 

函数然后显示在tableview中

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{ 
    var cell: UITableViewCell = UITableViewCell() 
    cell.textLabel?.text = filteredArrayResults[indexPath.row] 
    return cell 
} 

经滤波的阵列结果在这里,我需要的任何行被选择到,则指标值匹配到包含一个“id”另一个阵列和用于在一个函数来抓住所选品牌下的所有产品。

任何想法?

回答

1

一个可能的解决方案是创建保存文本和brandId一个结构:

struct FilterResult { 
    var name: String 
    var brandId: Int 
} 

然后填写filteredArrayResults与结构:

for i in 0..<brandNames.count 
    { 
     var substring: NSString = brandNames[i] as NSString 
     if let temp = substring.lowercaseString.rangeOfString(txtBrand.text) 
     { 
      filteredArrayResults.append(FilterResult(name: substring, brandId: i)) 
     } 
     autocompleteTableView.reloadData() 
    } 
} 

然后,在你cellForRowAtIndexPath你有权访问原始索引,您可以将其存储在单元的tag以供进一步参考:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{ 
    var cell: UITableViewCell = UITableViewCell() 

    let filterResult = filteredArrayResults[indexPath.row] as FilterResult 

    cell.textLabel?.text = filterResult.name 
    cell.tag = filterResult.brandId 

    return cell 
} 

(这是我的头,没有叮叮。可能有一些问题,自选,虽然)

+0

感谢您的答复,Xcode不是让我进入两行 cell.textLabel?的.text = filterResult.name cell.tag = filterResult.brandId CalculatorViewController.FilterResult.Type没有名为'name'的成员 – 2014-10-02 07:24:18

+0

Try:'let filterResult = filteredArrayResults [indexPath.row] as FilterResult'。我编辑了我的答案。 – zisoft 2014-10-02 07:37:09

相关问题