我想将参数传递给 timer 中名为 selector 的函数。特别是对cell
的引用,以便我可以更新 UI 中的内容。
所以我想要这样的东西:
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
}
如果数据发送正确,我期待更多这样的选项:
答案 0 :(得分:10)
使用userinfo
设置您的计时器timer = Timer.init(timeInterval: 1.0, target: self, selector: #selector(downloadTimer(cell: cell), userInfo: data, repeats: true)
并获取userinfo如下
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
}
答案 1 :(得分:8)
在创建Timer时传入所需的数据作为userInfo参数:
timer = Timer.init(timeInterval: 1.0, target: self, selector: #selector(downloadTimer(_:), userInfo: myData, repeats: true)
并使回调看起来像:
func downloadTimer(_ timer: Timer) {
// access timer.userInfo here
}