Swift开发PDFKit无Storyboard场景:如何添加退出PDF的返回按钮?
实现PDF页面退出功能的解决方案
方法一:利用导航栏添加返回按钮(推荐,适配iOS导航逻辑)
如果你的PDF显示页面是通过UINavigationController的push方式进入的,直接在控制器的viewDidLoad中添加导航栏返回按钮:
override func viewDidLoad() { super.viewDidLoad() // 创建自定义返回按钮 let backButton = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(backAction)) navigationItem.leftBarButtonItem = backButton } @objc private func backAction() { // 从导航栈弹出当前页面 navigationController?.popViewController(animated: true) // 如果是通过present方式弹出的PDF页面,替换为下面这行: // dismiss(animated: true) }
方法二:添加悬浮退出按钮(不依赖导航栏)
如果没使用导航控制器,直接在PDF视图上层添加悬浮按钮,注意要将按钮添加到self.view而非PDFView内部,确保层级在PDFView之上:
修改你的displayPdf方法,添加按钮逻辑:
private func displayPdf(FileName:String) { let pdfView = createPdfView(withFrame: view.bounds) if let pdfDocument = createPdfDocument(forFileName: FileName) { view.addSubview(pdfView) pdfView.autoScales = true pdfView.document = pdfDocument // 创建退出按钮 let exitButton = UIButton(type: .system) exitButton.setTitle("退出", for: .normal) exitButton.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium) exitButton.addTarget(self, action: #selector(exitAction), for: .touchUpInside) // 设置按钮位置(左上角,适配安全区域) let safeTop = view.safeAreaInsets.top exitButton.frame = CGRect(x: 20, y: safeTop + 20, width: 60, height: 40) // 添加到主视图,确保在PDFView上层 view.addSubview(exitButton) // 若按钮被遮挡,可调用此方法置顶 // view.bringSubviewToFront(exitButton) } } @objc private func exitAction() { // 根据页面跳转方式选择退出逻辑 navigationController?.popViewController(animated: true) // present方式弹出的页面用: // dismiss(animated: true) }
注意:之前按钮无法显示大概率是因为将按钮添加到了
PDFView内部,或者层级被PDFView覆盖,将按钮添加到self.view并确保在PDFView之后添加即可解决。
内容的提问来源于stack exchange,提问作者ريم
相关产品推荐
相关产品推荐

