Кнопка Share в Swift программно с использованием XIB - PullRequest
0 голосов
/ 28 апреля 2020

В настоящее время у меня есть приложение для каталога, которое я создаю в стиле iOS Фотографии, но я не использую раскадровки, а xibs. Я изо всех сил пытаюсь создать рабочую кнопку общего доступа, так как кнопка общего доступа находится в PhotoViewerViewController, а изображение для совместного использования находится в PhotoViewerCell. Код, который у меня есть:

PhotoViewerViewController.swift

import UIKit

class PhotoViewerViewController: UIViewController {
    //MARK: - Outlets
    @IBOutlet weak var collectionView:UICollectionView!


    //MARK: - Variables
    var album:Album!
    var photoIndex:Int!
    var initialScrollDone = false


    //MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()

        let nib = UINib(nibName: "PhotoViewerCell", bundle: nil)
        collectionView.register(nib, forCellWithReuseIdentifier:
            "PhotoViewerCell")

        let shareButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareImage))
        navigationItem.rightBarButtonItem = shareButton
    }

    override func viewDidLayoutSubviews() {
        if (!self.initialScrollDone) {
            self.initialScrollDone = true
            scrollToPhoto(index: photoIndex, animated: false)
        }
    }


    //MARK: - Functions
    func scrollToPhoto(index:Int, animated:Bool) {
        let photoIndexPath = IndexPath(item: index, section: 0)
        collectionView.scrollToItem(at: photoIndexPath, at: .centeredHorizontally, animated: animated)
    }

    @objc func shareImage(_ sender: UIBarButtonItem) {
        //TODO: share displayed image

        let activityVC = UIActivityViewController(activityItems: [self.album.photos], applicationActivities: nil)
        activityVC.popoverPresentationController?.sourceView = self.view

        self.present(activityVC, animated: true, completion: nil)

    }


    //MARK: - Delegates
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        //set new photoIndex
        let x = targetContentOffset.pointee.x
        photoIndex = Int(x / collectionView.bounds.width)

        //reset zoom level in previous and next cells
        if(photoIndex <= 0 || photoIndex >= album.photos.count) {
            return
        }

        let previousIndexPath = IndexPath(item: photoIndex - 1, section: 0)
        let previousCell = collectionView.cellForItem(at: previousIndexPath) as? PhotoViewerCell
        previousCell?.resetZoom()

        let nextIndexPath = IndexPath(item: photoIndex + 1, section: 0)
        let nextCell = collectionView.cellForItem(at: nextIndexPath) as? PhotoViewerCell
        nextCell?.resetZoom()
    }
}

extension PhotoViewerViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return album.photos != nil ? album.photos.count : 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoViewerCell", for: indexPath) as! PhotoViewerCell

        cell.setupCell(photo: album.photos[indexPath.row])

        return cell
    }
}

extension PhotoViewerViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        //TODO: handle selection if needed

    }
}

extension PhotoViewerViewController : UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.bounds.width, height: collectionView.bounds.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

        coordinator.animate(alongsideTransition: {(_) in
            self.collectionView.collectionViewLayout.invalidateLayout()
            self.scrollToPhoto(index: self.photoIndex, animated: false)
        }, completion: nil)
    }
}

и PhotoViewerCell.swift

import UIKit

class PhotoViewerCell: UICollectionViewCell, UIScrollViewDelegate {
    //MARK: - Outlets
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var imageView: UIImageView!



    //MARK: - Functions
    func setupCell(photo:Photo) {
        resetZoom()
        imageView.image = photo.image
    }

    func resetZoom() {
        scrollView.zoomScale = 1
    }


    //MARK: - Delegates
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
}

Все работает нормально, вид деятельности появляется без каких-либо опций. .. Любая помощь с благодарностью. Спасибо!

...