I built an app that fetch all the photos from Instagram user via Instagram API and show them ordered in CollectionView.
Now, when the user tap on a photo the photo will open in a UIView
to show that image - basically the user can pinch to zoom and other options that can't be in the Instagram app.
What I'm trying to do is - swipe the image to move to the next image. I thought about using ScrollView which is not a big deal.
THE PROBLEM IS that I don't know how to call the next photo in the collection view.
just store selected index path. Next photo will be next index path.
Example: self.selectedIndexPath = indexPath
- save
Then get next index path or nil (if not exist):
func nextIndexPath() -> NSIndexPath? {
if collectionView.numberOfItemsInSection(selectedIndexPath.section) > selectedIndexPath.item {
return NSIndexPath(forItem: selectedIndexPath.item + 1, inSection: selectedIndexPath.section)
}
return nil
}
Then you could use it to get next photo, something like this:
if let indexPath = nextIndexPath() {
let photo = photos[indexPath.item]
}
PS item
is the same as row
, but for CollectionView, because row
wrong name for it. So it's preferable to use item
in collection views
You can use delegation something like this, have your view displaying the image call nextPhoto() when need an the collection view will supply.
struct Photo {
var image:UIImage?
}
class CustomCollectionView: UICollectionViewController{
var dataSource:[Photo]! = []
var selectedIndex:NSIndexPath!
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension CustomCollectionView: UpdatePhoto {
func nextPhoto() -> Photo?{
let nextIndex = selectedIndex.row + 1
// update selected index
selectedIndex = NSIndexPath(forRow: nextIndex, inSection: 0)
return dataSource[selectedIndex.row];
}
func previousPhoto() -> Photo? {
let previousIndex = selectedIndex.row - 1
// update selected index
selectedIndex = NSIndexPath(forRow: previousIndex , inSection: 0)
return dataSource[selectedIndex.row];
}
}
protocol UpdatePhoto {
func nextPhoto() -> Photo?
func previousPhoto() -> Photo?
}
class PhotoDisplayingView:UIView{
var photo:Photo
var delegate:UpdatePhoto?
required init(photo:Photo){
self.photo = photo
super.init(frame: CGRect(origin: CGPointZero, size: photo.image!.size))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}
You'll do something like this when handling the gesture var nextImage = delegate.nextPhoto()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.