我在一个视图控制器中有3个单独的collectionViews,每个集合视图中有3个项目。我希望用户从每个collectionView中选择一个单元格,并根据选择的内容连接到特定的视图控制器。
我知道这可能涉及到一些逻辑,我现在正在使用“If,Else”语句。我也使用了didSelectItemAt,对每个集合视图的单元格使用performSegueWithIdentifier,但是,当用户只选择一个collectionView中的一个单元格时,分段总是会发生,我还没有弄清楚哪里出错了。
这是我一直在使用的代码;
class ViewController: UIViewController, UICollectionViewDelegate,UICollectionViewDataSource {
@IBOutlet weak var collectionViewRed: UICollectionView!
@IBOutlet weak var collectionViewBlue: UICollectionView!
@IBOutlet weak var collectionViewGreen: UICollectionView!
var redColors = ["Red", "Infrared", "Crimson"]
var blueColors = ["Blue", "Light Blue", " Navy Blue"]
var greenColors = ["Green", "Lime Green", "Forest Green"]
func collectionView(_ collectionView: UICollectionView, didSelectItemAt: indexPath: IndexPath) {
if collectionView == self.collectionViewRed {
let cellA = collectionViewRed.cellForItem(at: indexPath) as!
CollectionViewCell
self.performSegue(withIdentifier: "ShowNextView", sender nil)
} else if collectionViewBlue == self.collectionViewBlue {
let cellB = collectionViewBlue.cellForItem(at: indexPath) as!
CollectionViewCell
self.performSegue(withIdentifier: "ShowNextView", sender: nil)
} else if collectionView == self.collectionViewGreen {
let cellC = collectionViewGreen.cellForItem(at: indexPath) as!
CollectionViewCell
}
}
当用户点击红色CollectionView中的“红色”时,它执行到下一个ViewController的分段,而不是当用户从"redCollectionView“中选择”红色“时,然后从"blueCollectionView”中选择“蓝色”,最后从"greenCollectionView“中选择”绿色“,以执行到特定ViewController的分段。
我应该使用什么代码来允许用户从每个collectionView中选择1个项目,然后执行分段?
发布于 2019-04-08 05:55:37
您应该有3个Bools来存储所有集合视图的选定单元格的状态。
将它们初始化为false
var isFirstCollectionViewSelected = false
var isSecondCollectionViewSelected = false
var isThirdCollectionViewSelected = false
// You can also use this for the states, in that case you would not even need the above variables
var firstSelectedIndex: Int?
所以你的didSelectItemAt
看起来会像这样
func collectionView(_ collectionView: UICollectionView, didSelectItemAt: indexPath: IndexPath) {
if collectionView == self.collectionViewRed {
isFirstCollectionViewSelected = true
self.firstSelectedIndex = indexPath.row
// Add logic here when this cell is selected
} else if collectionView == self.collectionViewBlue {
isSecondCollectionViewSelected = true
// Add logic here when this cell is selected
} else if collectionView == self.collectionViewGreen {
isThirdCollectionViewSelected = true
// Add logic here when this cell is selected
}
performSegueIfAllAreSelected()
}
performSegueIfAllAreSelected()
会在哪里
func performSegueIfAllAreSelected() {
if isFirstCollectionViewSelected, isSecondCollectionViewSelected, isThirdCollectionViewSelected {
if self.firstSelectedIndex == 1 {
self.performSegue(withIdentifier: "ShowNextView", sender: nil)
} else {
//
}
}
}
https://stackoverflow.com/questions/55563887
复制相似问题