我正在尝试获取 Collection View 中第一个选定的单元格。它显示为零,但在应用程序中显示了单元格。 clientCollectionView 也将为零。这是我正在尝试使用的功能
func currentClient() -> Client? {
let idx = self.clientsCollectionView?.indexPathsForSelectedItems?.first
guard let firstSelected = idx?.row else {
return nil
}
return clients()[firstSelected]
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return clients().count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "clientCollectionViewCell", for: indexPath)
if let cell = cell as? ClientCollectionViewCell {
cell.client = clients()[indexPath.row]
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
populateExerciseFields()
}
最佳答案
func currentClient() -> Client? {
// You haven't really explained what "clientsCollectionView" is
// I suspect you just need to replace it with a reference to the
// actual collection view, as shown below.
let idx = self.collectionView?.indexPathsForSelectedItems?.first
guard let firstSelected = idx?.row else {
return nil
}
return clients()[firstSelected]
}
请参见此处:https://developer.apple.com/documentation/uikit/uicollectionviewcontroller/1623983-collectionview
您可能正在引用其他一些实例...但不是与您的 Collection View Controller 关联的实例。
关于Swift 首先在 Collection View 中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49928763/