简体   繁体   中英

Programmatically replace UIImageView with PDFView in Swift

I have a UIImageView in my storyboard with an IBOutlet to my view controller. Is there a way to programmatically replace this with a PDFView and give the PDFView its constraints at runtime? I am changing views based on if I am displaying an image or a pdf.

Have a single UIView , linked to a IBOutlet to your ViewController, with the right constraints in your storyboard and add/remove the appropriate subviews at runtime (being either a UIImageView or a PDFView ).

For example, to add a PDFView as a subview filling the entire UIView (hereby named containerView ) :

import PDFKit

//...

let pdfView = PDFView()

pdfView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(pdfView)

pdfView.leadingAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.leadingAnchor).isActive = true
pdfView.trailingAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.trailingAnchor).isActive = true
pdfView.topAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.topAnchor).isActive = true
pdfView.bottomAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.bottomAnchor).isActive = true

//add pdf content 
guard let path = Bundle.main.url(forResource: "example", withExtension: "pdf") else { return }

if let document = PDFDocument(url: path) {
    pdfView.document = document
}

For an UIImageView :

let imageName = "yourImage.png"
let image = UIImage(named: imageName)
let imageView = UIImageView(image: image!)

imageView.frame = CGRect(x: containerView.frame.origin.x, 
                         y: containerView.frame.origin.y, 
                         width: containerView.frame.size.width, 
                         height: containerView.frame.size.height)
containerView.addSubview(imageView)

Don't forget to remove your subviews when necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM