同时运行两个定时器

时间:2017-08-28 14:24:15

标签: ios iphone swift multithreading timer

我正在开发一个应用程序,可以同时随机选择两个 CollectionView 单元格。通过向Handler添加不同的Runnables,我在android中实现了这一点。 在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 Cell Selection似乎没有选择两个单元格。我是iOS的新手,因此对iOS中的多线程/多时间计时器并不了解。

1 个答案:

答案 0 :(得分:1)

这一行只调用了委托方法:

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

如果要在UI中选择项目,则必须调用另一种方法,如下所示:

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

您可能还想设置属性:

collectionView.allowsMultipleSelection = true