如何在UICollectionView中获取每个选定单元格的按钮标题?

问题描述 投票:0回答:2

我有一个按钮的集合视图,如下图所示。我希望能够选择多个这些单元格,并在这样做时将每个选定按钮的标题传递给一个字符串数组。

UICollectionView - each cell has a button with a title

UICollectionView位于WordViewController类中

class WordViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout

UICollectionViewCell就在它自己的文件中。

import UIKit

class WordCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var wordView: UIButton!

@IBAction func buttonTapped(_ sender: UIButton) {
    if wordView.isSelected == true {
        wordView.isSelected = false
        wordView.backgroundColor = UIColor.blue
    }else {
        wordView.isSelected = true
        wordView.backgroundColor = UIColor.green
    }  
}

}

我对Swift很新,我一直在试图找到答案,但我无法弄清楚。我怀疑我可能必须使用indexPathsForSelectedItems但我已经尝试过这个并且无法使其正常工作。

func indexSelected () {
        let collectionView = self.collectionView
        let indexPath = collectionView?.indexPathsForSelectedItems?.first
        print(indexPath!)
        let cell = collectionView?.cellForItem(at: indexPath!) as? WordCollectionViewCell
        let data = cell?.wordView.currentTitle
        print(data!)

}

我不确定我在设置CollectionView的方式上是否存在根本性的错误,或者是否与使用CollectionViewCells中的按钮有关。

任何帮助将非常感激。

swift uicollectionview uicollectionviewcell
2个回答
1
投票

这是你可以做到的一种方式。首先获取所选单元格的indexPaths。然后遍历indexPaths并获取每个IndexPath的单元格(将它们转换为自定义CollectionViewCell以访问您的按钮)。现在,您可以将每个标题附加到数组以保存它们。

var titleArray = [String]()

    guard let selectedIndexPaths = collectionView.indexPathsForSelectedItems else { return }

    for indexPath in selectedIndexPaths {
        if let cell = collectionView.cellForItem(at: indexPath) as? WordCollectionViewCell {
            self.titleArray.append(cell.yourButton.titleLabel?.text)
        }
    }

0
投票

欢迎来到SO。这听起来有点像X / Y问题:在这种情况下,您询问如何实现特定(通常是次优的)解决方案,而不是首先询问如何解决问题。

您不应将集合视图中的视图视为保存数据。 (按钮是视图。)

您应该使用该按钮找出用户点击的单元格的indexPath,然后在数据模型中查找信息。

您应该设置一个结构数组(或数组数组,如果您的集合视图位于行的各个部分中。)每个结构都应包含单元格的当前设置。

您的collectionView(_:cellForItemAt:)方法应该使用结构数组来配置您的显示销售。

当用户点击按钮并选择单元格时,您应该在相应的IndexPath处更新结构,然后告诉集合视图更新这些单元格。

如果您需要对所选单元格执行某些操作,则应该向集合视图询问所选单元格的数组,您应该使用这些IndexPaths索引到模型数组并获取每个IndexPath的结构,然后查找数据你需要。

编辑:

你可以使用一个非常简单的UICollectionView扩展来查找集合视图中任何视图的indexPath(并且按钮是一个视图,如上所述......)

extension UICollectionView {
    func indexPathForCellContaining( view: UIView) -> IndexPath? {
        let viewCenter = self.convert(view.center, from: view.superview)
        return self.indexPathForItem(at: viewCenter)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.