Swift 如何创建公共函数以在UICollectionView中显示选定单元格的indexPath

Swift 如何创建公共函数以在UICollectionView中显示选定单元格的indexPath,swift,uicollectionview,uicollectionviewcell,Swift,Uicollectionview,Uicollectionviewcell,在我的应用程序中,我需要一个公共函数/public var,其中我需要知道所选单元格的indexPath。由于我是一个新的程序员,我有一些想法如何使它,但没有一个工作还没有 我只是想,我可以从类中的任何地方访问所选的indexPath。所以我需要一些建议/帮助 func selectedColor(){ 让cell=gamePad.dequeueReusableCell(带有reuseidentifier:“coloredCell”,for:indexath)作为!UICollectionVie

在我的应用程序中,我需要一个公共函数/public var,其中我需要知道所选单元格的
indexPath
。由于我是一个新的程序员,我有一些想法如何使它,但没有一个工作还没有

我只是想,我可以从类中的任何地方访问所选的indexPath。所以我需要一些建议/帮助

func selectedColor(){
让cell=gamePad.dequeueReusableCell(带有reuseidentifier:“coloredCell”,for:indexath)作为!UICollectionViewCell
让selectedCell=gamePad.indexPathForItem(在:CGPoint)
}

UICollectionView上的indexPathsForSelectedItems


我同意Dávid pászor的观点,但这是我第一次帮助你。您需要实现UITableView的委托。我想它会是这样的:

class TableViewController: UIViewController {
    @IBOutlet var tableView: UITableView!

    var selectedIndexPath: IndexPath?

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
    }
}

extension TableViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedIndexPath = indexPath
    }
}
class ViewController: UIViewController {
    @IBOutlet var collectionView: UICollectionView!

    var selectedIndexPath: IndexPath?

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.delegate = self
    }
}

extension ViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectedIndexPath = indexPath
    }
}
注意:对于UICollectionView,它是相同的,但您需要实现UICollectionViewDelegate,如下所示:

class TableViewController: UIViewController {
    @IBOutlet var tableView: UITableView!

    var selectedIndexPath: IndexPath?

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
    }
}

extension TableViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedIndexPath = indexPath
    }
}
class ViewController: UIViewController {
    @IBOutlet var collectionView: UICollectionView!

    var selectedIndexPath: IndexPath?

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView.delegate = self
    }
}

extension ViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectedIndexPath = indexPath
    }
}

另外,如果你不需要知道手机被点击的时间,那么你可以使用(@rmaddy)

而不是明目张胆地说你尝试了某个东西,但没有效果,你应该实际提出你的问题并包含你尝试过的代码,即使它不起作用。如果人们看到你的努力,他们会更乐于助人,而且纠正你自己的代码,而不是给你一大块从头开始编写的代码,也会对你更有帮助。因为你对编码还不熟悉,让我解释一下,很少有理由在公共变量中维护此类信息!您应该只为变量提供它们真正需要的范围,而全局变量非常罕见。@Barns好的,谢谢。我应该怎么看,哪个单元格被选中了?我用UICollectionView来做,这样解决方案就不起作用了,我想这些都不需要了。UICollectionView和UITableView都已经提供了获取当前选定索引路径的属性。