如何在swift中使用PdfKit为注释添加颜色或添加动作以突出显示注释

问题描述 投票:1回答:1

我的应用程序中有一些pdf,我在swift中使用PdfKit。现在我想突出显示pdf文档中的所有超链接。我尝试使用PDFAnnotationSubtype.highlight和PDFAnnotationSubtype.link,但在这两种情况下我都无法实现我的目标。

对于PDFAnnotationSubtype.highlight - 点击链接我无法添加操作。

对于PDFAnnotationSubtype.link - 我无法为链接设置颜色或背景颜色。

这是我的代码请纠正我,如果我在这里遗漏了一些东西。

//here i get my pdf from document directory
let filePAth = (self.getDirectoryPath() as NSString).appendingPathComponent(webURLString)
    let fileURL = URL(fileURLWithPath: filePAth)

    let document = PDFDocument(url: fileURL)

    self.pdfView.displayMode = .twoUpContinuous
    self.pdfView.displayDirection = .horizontal
     pdfView.usePageViewController(true, withViewOptions: [UIPageViewController.OptionsKey.interPageSpacing: 0])

    //here is the hack 
    //i am getting annotation  
   let count = document?.pageCount

    for i in 0 ..< count! {

        let page = document?.page(at: i)
        let annotationArray = page1?.annotations

      for annotationObj in annotationArray! {
            if annotationObj.type! == "Link" {

                //case 1: highlights hyperlinks links but
                //added action does not work
                let annotation = PDFAnnotation(bounds: obj.bounds, forType: PDFAnnotationSubtype.highlight, withProperties: nil)

                annotation.color = UIColor.red
                annotation.isHighlighted = true

                // highlights all the hyperlinks with red color
                // but added action does not work here

                let url = URL(string: "http://google.com/")
                annotation.action = PDFActionURL(url: url!)

               page?.addAnnotation(annotation)

             //case 2: does not highlights hyperlinks links with red 
             //color but added action works

                let annotation = PDFAnnotation(bounds: obj.bounds, forType: PDFAnnotationSubtype.link, withProperties: nil)
                // no effect 
                annotation.color = UIColor.red
                annotation.isHighlighted = true

                // does not highlight all the hyperlinks with red 
                // but added action works here

                let url = URL(string: "http://google.com/")
                annotation.action = PDFActionURL(url: url!)

               page?.addAnnotation(annotation)

            }
        }
    }

我能找到方法。有谁能建议一些事情?图像是代码中提到的案例1的结果。 enter image description here

xcode10 ios12 swift4.2 ios-pdfkit
1个回答
1
投票

即使它不是一个合适的解决方案,尽管它是一个黑客。

步骤1 - 创建链接注释并将现有注释操作添加到新链接注释。

let linkAnnotation = PDFAnnotation(bounds: obj.bounds, forType: PDFAnnotationSubtype.link, withProperties: nil)
linkAnnotation.action = obj.annotation

第2步 - 在突出显示的注释后添加新的链接注释到页面。

page?.addAnnotation(linkAnnotation)

如果这对你有用,请试着告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.