[英]Programmatically replace UIImageView with PDFView in Swift
I have a UIImageView in my storyboard with an IBOutlet to my view controller. 我的情节提要中有一个UIImageView,带有一个IBOutlet的视图控制器。 Is there a way to programmatically replace this with a PDFView and give the PDFView its constraints at runtime?
有没有一种方法可以通过编程方式将其替换为PDFView并在运行时赋予其PDFView约束? I am changing views based on if I am displaying an image or a pdf.
我根据显示图像还是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
). 具有一个
UIView
,将IBOutlet链接到ViewController,并在情节PDFView
具有正确的约束,并在运行时添加/删除适当的子视图(可以是UIImageView
或PDFView
)。
For example, to add a PDFView as a subview filling the entire UIView (hereby named containerView
) : 例如,要添加一个PDFView作为填充整个UIView的子视图(此处称为
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 : 对于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. 不要忘记在必要时删除子视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.