显示在集合视图控制器之间选择的图像
Displaying image selected between collection view controllers
我有 structs
如下 First Collection View Controller
struct Area{
var name = String()
var image = String()
}
var area = [Area]()
并在 Second Collection View Controller
struct AreaSelected {
var imageSelected = String()
}
var areaSelected = [AreaSelected]()
我想在 Second Collection View Controller
中显示从 First Collection View Controller
中选择的图像。
所以我这样做是为了将它们导航到位于 didSelectItemAt indexPath
let indexPaths = self.areaCV!.indexPathsForSelectedItems!
var indexPath = indexPaths[0] as IndexPath
let detailViewController = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as? SecondViewController
detailViewController?.areaSelected = [self.area[(indexPath as NSIndexPath).item]]
他们我得到以下编译器错误
Cannot convert value of type 'Area' to expected element type 'AreaSelected'
如何摆脱这个错误?
基本上
let selectedArea = self.area[(indexPath as NSIndexPath).item]
detailViewController?.areaSelected = [AreaSelected(imageSelected: selectedArea.name)]
PS:您在不同的视图控制器中使用了不同的(不兼容的)类型,因此绝对不能直接将其分配给彼此。
PSS:在 ViewController 之间的 CellSelected 上设置 segue 更容易、更清晰、更好,并在 func prepare(for segue:UIStoryboardSegue, sender: Any?)
areaSelected
错误消息很清楚,您的第一个结构类型为:FirstCollectionViewController.Area
,第二个结构类型为SecondCollectionViewController.AreaSelected
。两者就像 Int
和 String
一样不同,你不能将一个分配给另一个,就像你不能做 let number: Int = "Of course no"
一样。但是你可以定义一个通用类型:
protocol AreaDescription {
var image: String { get }
}
class FirstVC: ... {
struct Area: AreaDescription {
var name: String
var image: String
}
}
class SecondVC: ... {
struct AreaSelected: AreaDescription {
var name: String
var image: String
}
}
并将您的 属性 设置为:
var areaSelected = [AreaDescription]()