所以我正在创建一个 UiCollectionView。您可以滚动浏览 Collection View 中的一组图像,每当您点击其中一张图像时,它都会带您进入一个单独的 View Controller 并显示您从 UICollectionView 中点击的图像。我看了教程并一步一步地遵循,但我不知道我做错了什么。我可以查看 Collection View 并滚动它,但是一旦我点击其中一张图像,它就不会转到单独的 View Controller 。我已经检查了我的类和标识符。我都正确了。
collectionView
是一个名为collectionView
的 socket
collectionViewCell
中的 UIimage
是一个名为
collectionViewCell
标识符是“Cell”
collectionViewCell
类是 OurCell
将保存图像的viewController
称为secondViewController
以下是 ViewController
类文件的代码:
@IBOutlet weak var collectionView: UICollectionView!
let imageArray = [UIImage(named: "EliHouse1" ), UIImage(named: "EliHouse2"), UIImage(named: "EliHouse3" ), UIImage(named: "iPod" )]
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.imageArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! OurCell
cell.ourImage?.image = self.imageArray[indexPath.row]
return cell
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "showImage"
{
let indexPaths = self.collectionView!.indexPathsForSelectedItems!
let indexPath = indexPaths[0] as NSIndexPath
let vc = segue.destination as! SecondViewController
vc.image = self.imageArray[indexPath.row]!
}
}
这是 OurCell
类文件的代码
@IBOutlet weak var ourImage: UIImageView!
这是 SecondViewController
类文件的代码
@IBOutlet weak var imageView: UIImageView!
var image = UIImage()
override func viewDidLoad() {
super.viewDidLoad()
self.imageView.image = self.image
// Do any additional setup after loading the view.
}
我在代码中运行它,我可以查看和滚动单元格,但每当我点击图像时,它不会将我带到 SecondViewController
并且什么也没有发生。有人有什么想法吗?我究竟做错了什么?
最佳答案
在你的collectionView类中,你应该添加如下内容:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let identifier = "showImage"
if segue.identifier == identifier {
let indexPath = collectionView.indexPathsForSelectedItems
if let indexPath = indexPath?.first,
let cell = collectionView(rssCollectionView, cellForItemAt: indexPath) as? OurCell,
let image = cell.ourImage (or something like this to retrieve the picture) {
let showImage = segue.destination as? SecondViewController
showImage?.image = image
}
}
此外,在 Storyboard 中,您需要从 collectionView 单元格中命令并将其拖动到另一个第二 View Controller ,然后选择所需类型的 segue,然后选择用于 segue 的行并在标识 rune 本字段中添加“showImage”。
关于ios - 在 UICollectionView Swift 3 的单独 View Controller 中查看图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41712053/