我在视图控制器中有一个UICollectionView。当用户单击其中一个图像时,它将转到单独的页面以打开图像。我希望每次都不要回到画廊更换图片,向左或向右滑动以获得下一张或上一张图片。
我已经看到了做“pagingEnabled = true”的答案但是你把它放在哪里呢?
我是swift的新手。
以下是我的代码。我在这里先向您的帮助表示感谢。
ViewController.swift
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate
{
@IBOutlet weak var collectionView: UICollectionView!
let appleProducts = ["iPhone", "Apple Watch", "Mac", "iPad"]
let imageArray = [UIImage(named: "pug"), UIImage(named: "pug2"), UIImage(named: "pug3"), UIImage(named: "pug4")]
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return self.appleProducts.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell
cell.imageView?.image = self.imageArray[indexPath.row]
cell.titleLabel?.text = self.appleProducts[indexPath.row]
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
self.performSegueWithIdentifier("showImage", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "showImage"
{
let indexPaths = self.collectionView!.indexPathsForSelectedItems()!
let indexPath = indexPaths[0] as NSIndexPath
let vc = segue.destinationViewController as! NewViewController
vc.image = self.imageArray[indexPath.row]!
vc.title = self.appleProducts[indexPath.row]
}
}
}
CollectionViewCell.swift
import UIKit
class CollectionViewCell: UICollectionViewCell
{
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
}
NewViewController.swift
import UIKit
class NewViewController: UIViewController
{
@IBOutlet weak var imageView: UIImageView!
var image = UIImage()
override func viewDidLoad()
{
super.viewDidLoad()
self.imageView.image = self.image
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
答案 0 :(得分:0)
在点击后显示的视图控制器中,您应该进行水平滚动UICollectionView
。在此集合视图上,将其pagingEnabled
属性设置为true。
接下来要做的是重新格式化父视图控制器中的prepareForSegue
方法,将整个图像数组传递给呈现的视图控制器以及选定的索引路径。
然后,在您呈现的视图控制器中,您应该将集合视图的数据源配置为显示所有图像,但请确保从父视图控制器传递的初始选定索引路径开始