【问题标题】:collectionView(collectionView, didSelectItemAt: indexPath) - Cannot call value of non-function type 'UICollectionViewcollectionView(collectionView, didSelectItemAt: indexPath) - 不能调用非函数类型的值'UICollectionView
【发布时间】:2018-11-29 23:21:22
【问题描述】:

我有一个collectionView。我设置了它的 dataSource 和委托方法,当用户第一次进行选择时,我调用 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { },效果很好。

如果用户离开视图控制器并返回到它,我会在 viewWillAppear 中调用以下方法以编程方式强制选择单元格并滚动回最初选择的单元格。

let whateverCellWasChosen = 29
let indexPath = IndexPath(item: whateverCellWasChosen, section: 0)

collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .centeredHorizontally)

// problem is here
collectionView(self.collectionView, didSelectItemAt: indexPath)

但是在尝试调用 didSelectItem 的手动版本时,我不断收到以下错误:

不能调用非函数类型'UICollectionView'的值

错误源于接受collectionView的第一个参数。为什么会给我带来问题?

【问题讨论】:

  • 您不应该尝试自己调用任何数据源或委托方法。
  • 不知道你的上下文,但这里有一个类似的问题,我的回答与它齐头并进stackoverflow.com/questions/35039756/…
  • @rmaddy 这是一个日历,用户选择一个日期,我将日期保存在自定义委托中,他们弹出 vc,然后返回它,我希望他们仍然可以看到他们的日期选择。在视图 didAppear 中,我以编程方式滚动到日期,然后手动选择它。我读过一些帖子说使用 collectionView.selectItem(at: ...) 不会触发 didSelect stackoverflow.com/a/45412980/4833705
  • 如果您有要在 didSelectRowAt 中运行的代码,然后将其放入函数中并从 didSelectRowAtviewWillappear 调用它,没有尝试过,但我认为这不会像最后调用didSelectRowAt 的 ios 那样选择行
  • 这是否在与 CollectionView 委托相同的类的 viewWillAppear 中?

标签: ios swift uicollectionview


【解决方案1】:

使用

collectionView.delegate?.collectionView!(collectionView, didSelectItemAt: indexPath)

【讨论】:

  • 我正在尝试
  • 在 cmets @Jason 中询问“这是否在与 CollectionView 委托相同的类的 viewWillAppear 中”,这就是问题的根源。 collectionView 在一个单独的 Calendar 类中,我在其中创建了一个日历实例,我们称之为 vc1。由于 vc1 创建了 Calendar 的实例,但没有调用日历的 collectionView 的委托,因此它不会接受该参数。我将它包装在一个 if let 中并且它起作用了:'if let delegate = calendar.collectionView.delegate { delegate.collectionView!(calendar.collectionView, didSelectItemAt: indexPath) }'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-14
  • 1970-01-01
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多