iOS PDFView selectAll and currentSelection doesn't select text visually

65 views Asked by At

I'm trying to highlight a word (with Copy, Find, Translate buttons) by single tap in PDFView. Like this:

enter image description here

It is easy to identify the word that was tapped thanks to the method.

But then when I set selection to pdfView.currentSelection visually nothing happens. And this happens until I make a classic long tap on the text, which seems to "activate" the visual highlighting function. Then any setting pdfView.currentSelection displays selection.

Everything is the same with pdfView.selectAll(nil)

The problem is very similar to the problem with UITextView - but there is solution with textView.select(self) call before set selectedRange

if you try to call the method you will get a crash -[PDFView select:]: unrecognized selector sent to instance 0x105d0d120

You can try this code and you will see that the text is selected (in selectionChangeNotification), but visually nothing happens. But if you increase Dispatch interval and you will have time to select the text (word) with a long tap you will see how all the text is selected after asyncAfter firing.

import UIKit
import PDFKit

class ViewController: UIViewController {
    
    private var pdfView: PDFView?
        
    override func viewDidLoad() {
        super.viewDidLoad()
        
        guard let path = Bundle.main.url(forResource: "somePDF", withExtension: "pdf") else {
            return
        }
        
        let pdfView = PDFView()

        pdfView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(pdfView)
        pdfView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor).isActive = true
        pdfView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor).isActive = true
        pdfView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        pdfView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
        
        if let document = PDFDocument(url: path) {
            pdfView.document = document
        }
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(selectionChangeNotification),
            name: .PDFViewSelectionChanged,
            object: pdfView
        )
        self.pdfView = pdfView
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            self.pdfView?.selectAll(nil)
        }
    }
    
    @objc
    private func selectionChangeNotification() {
        print(pdfView?.currentSelection)
    }
}

UPD:

I checked on iOS 15.7.6 and it works. On iOS 17 doesn't.

UPD 2:

On iOS 16.4 (simulator) this also works.

0

There are 0 answers