簡體   English   中英

從其他類調用collectionview中的下一個圖像

[英]Calling next image in collectionview from other class

我構建了一個應用程序,可通過Instagram API從Instagram用戶獲取所有照片,並在CollectionView中顯示它們的順序。

現在,當用戶點擊照片時,照片將在UIView打開以顯示該圖像-基本上,用戶可以捏按縮放以及Instagram應用程序中無法提供的其他選項。

我想做的是-滑動圖像以移至下一張圖像。 我考慮過使用ScrollView沒什么大不了的。

問題是我不知道如何在收藏夾視圖中調用下一張照片。

只需存儲選定的索引路徑。 下一張照片將是下一個索引路徑。

示例: self.selectedIndexPath = indexPath保存

然后獲取下一個索引路徑或nil(如果不存在):

func nextIndexPath() -> NSIndexPath? {
  if collectionView.numberOfItemsInSection(selectedIndexPath.section) > selectedIndexPath.item {
      return NSIndexPath(forItem: selectedIndexPath.item + 1, inSection: selectedIndexPath.section)
  }
  return nil
}

然后,您可以使用它來獲取下一張照片,如下所示:

if let indexPath = nextIndexPath() {
  let photo = photos[indexPath.item]
}

PS itemrow相同,但對於CollectionView,因為它的row名稱錯誤。 因此,最好在集合視圖中使用item

您可以使用類似這樣的委托,讓您的視圖在需要集合視圖提供時顯示圖像調用nextPhoto()。

        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")
            }
        }
     }

處理手勢時,您將執行以下操作var nextImage = delegate.nextPhoto()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM