如何使用函数来选择UITableViewCell,而不用点击它?

问题描述:

我正在使用下面提到的数组填充我的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 –

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 
      } 

    } 

如果你的tableview是根据在序贯的方式排列,然后填充,您可以在else块做到这一点:找到过滤项在主项的最后一个对象的索引。它应该获取tableview的indexpath.row,它具有根据数组DS的单元格。您可以通过提供数组的索引并获取单元格来获取单元格cellForRowAtIndexPath,然后可以打开单元格的选择并重新加载索引路径。

目前我不在我的mac,因此我不能写代码,但我解释了找到它的逻辑。希望这可以帮助。

+0

该数组,只要你有乌尔MAC u能发送代码? –

有两种方法,我可以想到达到你想要的。

//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 
}