Faisal
Faisal

Reputation: 205

About sender.tag buttons

I have a problem with CellViewConnection. I have two storyboards:

But I have a problem. I made the code when I pressed the first button to show me the first PDF file with the sender.tag. But I did not get the result of the first button and the second button I get the same as the first PDF.

How can I make the first button to get the first and the second one gets the second PDF file?
Here is my code:

import UIKit
import PDFKit

@available(iOS 11.0, *)
@available(iOS 11.0, *)
@available(iOS 11.0, *)
@available(iOS 11.0, *)
@available(iOS 11.0, *)
@available(iOS 11.0, *)
@available(iOS 11.0, *)
@available(iOS 11.0, *)
@available(iOS 11.0, *)
@available(iOS 11.0, *)
@available(iOS 11.0, *)
class FirstARViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {


    @IBOutlet weak var collectionView: UICollectionView!
    var imagescv = ["ar1","ar2" ]

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.delegate = self
        collectionView.dataSource = self
    }




    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imagescv.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! cellimagesar

        cell.layer.cornerRadius = 5

        cell.layer.borderWidth = 1

        cell.myImages.image = UIImage(named: imagescv [indexPath.row])
        cell.myImages.contentMode = .scaleToFill


        cell.buttonMove.tag = indexPath.item
        cell.buttonMove.addTarget(self, action: #selector(self.buttonClicked), for: .touchUpInside)

        return cell
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 171, height: 250)
    }
    let me = PDFViewController()
    @objc func buttonClicked(_ sender: UIButton) {
        if (sender.tag == 0) {
            PDFimport()
            let pdfView = PDFView(frame: UIScreen.main.bounds)

            let url = Bundle.main.url(forResource: "AR1", withExtension: "pdf")

            let vc = UIDocumentInteractionController(url: url!)
            pdfView.document = PDFDocument(url: url!)
            view.addSubview(pdfView)
            vc.delegate = (PDFViewController() as UIDocumentInteractionControllerDelegate)
                  }

       else if (sender.tag == 1) {
            PDFimport()
            let pdfView = PDFView(frame: UIScreen.main.bounds)

            let url = Bundle.main.url(forResource: "AR2", withExtension: "pdf")

            let vc = UIDocumentInteractionController(url: url!)
            pdfView.document = PDFDocument(url: url!)
            view.addSubview(pdfView)
            vc.delegate = (PDFViewController() as UIDocumentInteractionControllerDelegate)
        }

    }

    func PDFimport()
    {
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "PDF") 
        self.present(nextViewController, animated:true, completion:nil)
    }
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {

        return self
    }

}

Second View:

import UIKit
import PDFKit
import QuickLook

@available(iOS 11.0, *)
@available(iOS 11.0, *)

class PDFViewController: UIViewController {

    lazy var document: UIDocumentInteractionController = {
        let pdfView = PDFView(frame: UIScreen.main.bounds)
        let url = Bundle.main.url(forResource: "", withExtension: "pdf")

        let vc = UIDocumentInteractionController(url: url!)
        pdfView.document = PDFDocument(url: url!)
        view.addSubview(pdfView)
        vc.delegate = (PDFViewController() as UIDocumentInteractionControllerDelegate)

        return vc

    }()

    override func viewDidLoad() {
        super.viewDidLoad()


       document.presentPreview(animated: true)



    }





    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }




    @IBOutlet weak var pdfView: PDFView!



    @IBAction func doAction1(_ sender: AnyObject) {

       document.presentOpenInMenu(from: view.bounds, in: view, animated: true)
    }




    @IBAction func save(_ sender: Any)
    {
       document.presentOptionsMenu(from: view.bounds, in: view, animated: true)


    }



    @IBAction func backbutton(_ sender: Any)
    {
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "back")
        self.present(nextViewController, animated:true, completion:nil)
    }



}

@available(iOS 11.0, *)
extension PDFViewController: UIDocumentInteractionControllerDelegate {


    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }

}

Upvotes: 1

Views: 1498

Answers (2)

Najam
Najam

Reputation: 1159

I got Your problem ...

cell.buttonMove.tag = indexPath.item
cell.buttonMove.addTarget(self, action: #selector(self.buttonClicked), for: .touchUpInside)

Now If you analyze code, you can see that you are calling function with no parameter, which means UIButton never assigns to your function's parameter, which eventually lead to the issue, your tag will always be zero by default that's why it always opens your first pdf file.

Please change your code something like this

cell.buttonMove.tag = indexPath.item
cell.buttonMove.addTarget(self, action: #selector(self.buttonClicked(_:)), for: .touchUpInside)

For more detail please check this answer

Upvotes: 0

iOS Geek
iOS Geek

Reputation: 4855

Here I had used same code as you are using

My CollectionView cellForItemAt

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

        //Adding Button reference No need to give Tags Differently 
        cell.StarImageButton.addTarget(self, action: #selector(HomeVC.FavouriteButtonHandler(sender:)), for: .touchUpInside)

        //Return cell
        return cell
    }

My button Handler Required

@objc func FavouriteButtonHandler (sender: UIButton)
    {
        //Lets get the button position as CGPoint
        let buttonPosition : CGPoint = sender.convert(CGPoint.zero, to: self.HotDealsCollectionView)

        //using CGPoint we can get index Path of cell in which button was clicked
        let indexPath : IndexPath = self.HotDealsCollectionView.indexPathForItem(at: buttonPosition)!

        //Now, Do any required operation as here I need to reload my collectionView cell 
        self.HotDealsCollectionView.reloadItems(at: [indexPath])

        //You can use the index path to iterate in array of pdf files like 
        **pdfArray[indexPath.row]** //And open it

        //as per in your case
       switch indexPath.row {
       case 0:
           //Required Code for opening Pdf at index 0
           break
        case 1:
           //Required Code for opening Pdf at index 1
           break
        default:
           print("No index FOund")
        } 
    }

Here I actually mean instead of using button Tags why Not to directly use selected index as we usually do in cellForItemAt

Upvotes: 2

Related Questions