同时运行两个定时器

同时运行两个定时器

问题描述:

我正在开发一个应用程序,它可以同时随机选择两个细胞。我已经通过向Handler添加不同的Runnable来实现这一点。 在iOS系统中选择一个单元工作完全正常使用此代码:同时运行两个定时器

let randomNumber1 = Int(arc4random_uniform(UInt32(numberOfItems))) 
     print("random1",randomNumber1) 
     let indexPath1 = IndexPath.init(row: randomNumber1, section: 0) 
     self.previousIndexpath1 = indexPath1 
     self.collectionView(self.imageCollectionView, didSelectItemAt: indexPath1) 
     myTimer1 = Timer.scheduledTimer(timeInterval: TimeInterval(0.5), target: self, selector: #selector(AdvanceCollectionViewController.selectRow1), userInfo: nil, repeats: true) 
     let deadlineTime1 = DispatchTime.now() + .seconds(5) 
     DispatchQueue.main.asyncAfter(deadline: deadlineTime1, execute: { 
      self.myTimer1.invalidate() 
      // self.performSegue(withIdentifier: "collectionToDetail", sender: self) 
     }) 

现在我想运行定时器两个线程,并在限期结束施展指数。对于我只是说这个代码创建另一个线程:

let randomNumber2 = Int(arc4random_uniform(UInt32(numberOfItems))) 
     print("random2",randomNumber2) 
     let indexPath2 = IndexPath.init(row: randomNumber2, section: 0) 
     self.previousIndexpath2 = indexPath2 
     self.collectionView(self.imageCollectionView, didSelectItemAt: indexPath2) 
     myTimer2 = Timer.scheduledTimer(timeInterval: TimeInterval(0.5), target: self, selector: #selector(AdvanceCollectionViewController.selectRow2), userInfo: nil, repeats: true) 
     let deadlineTime2 = DispatchTime.now() + .seconds(5) 
     DispatchQueue.main.asyncAfter(deadline: deadlineTime2, execute: { 
      self.myTimer2.invalidate() 
      // self.performSegue(withIdentifier: "collectionToDetail", sender: self) 
     }) 

当查看日志我可以登录两个线程。但UI单元选择似乎不选择两个单元。我是iOS新手,对iOS中的多线程/多时钟定时器不太了解。

此行只叫委托方法:

self.collectionView(self.imageCollectionView, didSelectItemAt: indexPath1) 

如果你想选择在UI的项目,你必须调用类似下面的另一种方法:

self.imageCollectionView.selectItem(at: indexPath1, animated: false, scrollPosition: .bottom) 

您可能希望设置属性以及:

collectionView.allowsMultipleSelection = true