![](/img/trans.png)
[英]Programmatically change the height and width of a UIImageView Xcode Swift
[英]Programmatically replace UIImageView with PDFView in Swift
我的情節提要中有一個UIImageView,帶有一個IBOutlet的視圖控制器。 有沒有一種方法可以通過編程方式將其替換為PDFView並在運行時賦予其PDFView約束? 我根據顯示圖像還是pdf來更改視圖。
具有一個UIView
,將IBOutlet鏈接到ViewController,並在情節PDFView
具有正確的約束,並在運行時添加/刪除適當的子視圖(可以是UIImageView
或PDFView
)。
例如,要添加一個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
}
對於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)
不要忘記在必要時刪除子視圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.