【发布时间】:2019-02-08 21:49:38
【问题描述】:
我有一个按钮的collectionView,如下图所示。我希望能够选择多个这样的单元格,然后将每个选定按钮的标题传递到字符串数组中。
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 中的按钮有关。
任何帮助将不胜感激。
【问题讨论】:
-
“怀疑我可能不得不使用 indexPathsForSelectedItems 但我已经尝试过但无法使其正常工作”但是在您显示的代码中,您没有尝试过。请展示一个实际的尝试。
-
对不起,我的尝试添加到问题中。
-
不过,这并不清楚,你想象的会导致
indexSelected被调用。 -
我有一个按钮,点击后会调用 indexSelected。
标签: swift uicollectionview uicollectionviewcell