2017-04-19 54 views
1

我正在使用下面提到的數組填充我的tableView。如果用戶搜索數組並找到了項目,那麼應該選擇該單元。如何使用函數來選擇UITableViewCell,而不用點擊它?

(
     { 
     barcode = 8901058847857; 
     image =   (
     ); 
     name = "Maggi Hot Heads"; 
     productTotal = "60.00"; 
     quantity = 3; 
    }, 
     { 
     barcode = 8901491101837; 
     image =   (
     ); 
     name = "Lays Classic Salted"; 
     productTotal = "20.00"; 
     quantity = 1; 
    } 
) 

我使用下述代碼來搜索條碼的數組,但我不知道如何進一步進行,如何在其他情況下,選擇tableViewCell。 有代碼寫入tableViewCell setSelected。

let namePredicate = NSPredicate(format: "barcode contains[c] %@",code) 
    let filteredArray = orderDetailsArray.filter { namePredicate.evaluate(with: $0) } 
    if filteredArray.isEmpty { 
     let alert = UIAlertController(title: "Alert", message: "Item not found in cart.", preferredStyle: UIAlertControllerStyle.alert) 
     alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { action in 
      self.scan() 
     })) 
     self.present(alert, animated: true, completion: nil) 
    }else{ 
     print("item found") 
     // Need to do selection here 
    } 
+0

您可以簡單地字符串數組,包含過濾條形碼和比較cellForRow –

回答

1
else{ 
     print("item found") 
     1. add to that object in separate array 

      yourMutableArr.append("scannedString") // which are scanned 
               recently 

     2. reload tableview 
      [yourTblView reloadData]; 

     3. In cellForRowAtIndexPath compare that barcodes with datasource array's barcode 

      let strBarcode: String = dict["barcode"][indexPath.row] 
      if yourMutableArr.contains(strBarcode) { 
       //addNewItem 
         cell.accessoryType = .Checkmark 
      } 

    } 
0

如果你的tableview是根據在序貫的方式排列,然後填充,您可以在else塊做到這一點:找到過濾項在主項的最後一個對象的索引。它應該獲取tableview的indexpath.row,它具有根據數組DS的單元格。您可以通過提供數組的索引並獲取單元格來獲取單元格cellForRowAtIndexPath,然後可以打開單元格的選擇並重新加載索引路徑。

目前我不在我的mac,因此我不能寫代碼,但我解釋了找到它的邏輯。希望這可以幫助。

+0

該數組,只要你有烏爾MAC u能發送代碼? –

1

有兩種方法,我可以想到達到你想要的。

//First 
let filteredArray = dataArray.filter{$0["barcode"]!.contains("8901058847857")} 

var tempArray = [Int]() 

for dict in filteredArray{ 

    tempArray.append(dataArray.index{$0 == dict}!) 
} 

//this will have the appropriate rows that you want selected based on your initial and non filtered array 
print(tempArray) 

現在你所要做的就是試着弄清楚如何在你的方法中使用它。 tempArray包含要選擇的行的索引,以匹配您的要求。現在,您只需撥打UITableViewselectRowMethod並通過indexPath即可立即行

如果您只想根據條件選擇行並且未使用filteredArray,那麼在其他數組中添加與您的條件匹配的元素是沒有意義的。您應該使用以下方法。

//Second approach 
var index = 0 
var tempArray = [Int]() 

for dict in dataArray{ 

    if (dict["barcode"]?.contains("8901058847857"))!{ 

     //Or just select the row at this index value 
     tempArray.append(index) 
    } 

    index += 1 
} 
相關問題