2014-10-02 30 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

相關問題