在Swift中向选择器函数传递参数

5
我希望能将一个参数传递给一个被定时器调用的函数,该函数作为选择器。具体来说,我需要传递对单元格的引用,以便在用户界面中更新某些内容。所以我想要做的事情类似于这样:
timer = Timer.init(timeInterval: 1.0, target: self, selector: #selector(downloadTimer(cell: cell), userInfo: nil, repeats: true)

函数

func downloadTimer(cell: InnerCollectionCell) {
    cell.progressBar.setProgress(downloadProgress, animated: true)
}

虽然我可能有点天真,认为这可以做到?

------ 编辑 ------

根据以下示例,但从单元格中通常无法获得预期结果

let innerCell: InnerCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifierInner, for: indexPath) as! InnerCollectionCell

timer = Timer.init(timeInterval: 1.0, target: self, selector: #selector(downloadTimer(_:)), userInfo: innerCell, repeats: true)


func downloadTimer(_ timer: Timer) {

    let cell = timer.userInfo

    cell. // no options as expected of a cell

}

enter image description here

我希望如果数据被正确发送,会有更多类似这样的选项:

enter image description here

2个回答

12

使用用户信息设置定时器

timer = Timer.init(timeInterval: 1.0, target: self, selector: #selector(downloadTimer(cell: cell), userInfo: data, repeats: true)

并获取以下用户信息:

func downloadTimer(_ timer: Timer) {
   let data = timer.userInfo
}

如下所示,但从单元格中未能像往常一样获得预期的结果

let innerCell: InnerCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifierInner, for: indexPath) as! InnerCollectionCell

timer = Timer.init(timeInterval: 1.0, target: self, selector: #selector(downloadTimer(_:)), userInfo: innerCell, repeats: true)


func downloadTimer(_ timer: Timer) {

    let cell = timer.userInfo as! InnerCollectionCell

    cell. // no options as expected of a cell

}

输入图像描述


抱歉,我把这个附件放错了位置,而且无法删除。 - Pippo
将cell强制转换为InnerCollectionCell - Harshal Valanda
让cell = timer.userInfo作为InnerCollectionCell。 - Harshal Valanda
那很有道理。谢谢。 - Pippo
嗨,我可以通过cancelPreviousPerformRequests停止计时器,请帮忙。 - famfamfam

9

在创建计时器时,将想要的数据作为userInfo参数传入:

timer = Timer.init(timeInterval: 1.0, target: self, selector: #selector(downloadTimer(_:), userInfo: myData, repeats: true)

并使回调函数看起来像:
func downloadTimer(_ timer: Timer) {
    // access timer.userInfo here
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接