我正在使用UICollectionView开发一个倒计时场景。我做了一个计时器,以1秒的间隔更新collectionView。单元格正确更改其内容。但是当我长按单元格时,菜单控制器经常显示在错误的位置。如何解决?
谢谢。
这是简单的测试代码。
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var time = 100
override func viewDidLoad() {
super.viewDidLoad()
collectionView.register(UINib(nibName: "TestCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell")
let timer = Timer(timeInterval: 1.0, target: self, selector: #selector(ViewController.timerFire(timer:)), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: .common)
}
@objc func timerFire(timer: Timer) {
if time == 0 {
timer.invalidate()
} else {
time -= 1
collectionView.reloadData()
}
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! TestCollectionViewCell
cell.label.text = "\(time)"
return cell
}
func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
print("perform")
}
extension ViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return true
}
}