在iOS开发中,UIImagePickerController取消按钮无法正常工作的问题可能是由于以下原因导致的:
以下是一个简单的示例代码,展示了如何使用UIImagePickerController和取消按钮:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
let cancelButton = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancelButtonTapped))
imagePickerController.navigationItem.leftBarButtonItem = cancelButton
present(imagePickerController, animated: true, completion: nil)
}
@objc func cancelButtonTapped() {
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// 处理选中的图片
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// 取消选择图片
picker.dismiss(animated: true, completion: nil)
}
}
在这个示例中,我们创建了一个UIImagePickerController实例,并将其代理设置为当前控制器。然后,我们添加了一个取消按钮,并为其设置了一个target和action方法。在代理方法中,我们处理了选中的图片和取消选择图片的情况。最后,我们在取消按钮的target和action方法中关闭了UIImagePickerController。
领取专属 10元无门槛券
手把手带您无忧上云