Swift 首先在 Collection View 中选择

标签 swift uicollectionview uicollectionviewcell

我正在尝试获取 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/

相关文章:

ios - 将单元格添加到可见的空 UITableView 显示白色背景

ios - Swift 3 - NSLayoutConstraint CollectionView 附加到另一个 View

ios - traitCollection 更改时更改单元格布局

ios - 动态调整 UICollectionView 大小以确保没有项目间间距

ios - 是否可以为 UICollectionView 中的每个单元格创建一个标题?

ios - 在 Swift 中解析 XML 属性

从公历到伊斯兰教的快速转换日期没有显示正确的日期

ios - 苹果 map 消耗太多内存

ios - 大型 UICollectionViewCell 在滚动时消失

ios - 如何使用 SDWebImage 调整下载的图像大小?