我是swift的新手,我在下面的逻辑中发现了一个糟糕的代码
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? VC1,
let index = collectionView?.indexPathsForSelectedItems?.first{
dest.selection = self.cellLabels[index.row]
}
if let dest2 = segue.destination as? VC2,
let index2 = collectionView?.indexPathsForSelectedItems?.first{
dest2.selection = self.cellLabels[index2.row]
}
if let dest3 = segue.destination as? VC3,
let index3 = collectionView?.indexPathsForSelectedItems?.first{
dest3.selection = self.cellLabels[index3.row]
}
}
基本上,我有多个视图控制器,我试图触及它,具体取决于哪个Cell被点击。
为什么我觉得这是错误的代码是因为有很多代码重复。 有没有更好的方法来构建它?
答案 0 :(得分:18)
我定义了协议:
protocol YourProtocolName: class {
var selection: String? { get set } // obviously, use whatever type that is appropriate in your case
}
让您的三个视图控制器类符合该协议,例如:
class VC1: UIViewController, YourProtocolName {
var selection: String?
...
}
然后:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? YourProtocolName,
let index = collectionView?.indexPathsForSelectedItems?.first {
dest.selection = cellLabels[index.row]
}
}
答案 1 :(得分:4)
clickedLink
答案 2 :(得分:2)
我会使用父类来处理所有三个ViewController类,并将共享变量放在父类中。 e.g。
class ParentViewControllerClass: UIViewController{
var selection: Int?
}
class VC1: ParentViewControllerClass{
}
class VC2: ParentViewControllerClass{
}
class VC3: ParentViewControllerClass{
}
然后你应该能够分配一次值。像:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let dest = segue.destination as? ParentViewControllerClass,
let index = collectionView?.indexPathsForSelectedItems?.first {
dest.selection = index
}
这样,无论调用三个子视图控制器中的哪一个,都将满足该语句
答案 3 :(得分:1)
试试这个:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "segueIdentifier", sender: collectionView.cellForItem(at: indexPath))
}