gpt4 book ai didi

swift - 如何从其他类访问相机代码并稍后重用?

转载 作者:行者123 更新时间:2023-11-30 11:26:54 26 4
gpt4 key购买 nike

我有一些代码可以访问 UIImagePickerController 并将其保存在图像中。我不想每次要用的时候都重写这个,那么我还能怎么写呢?请原谅,我只是再次将其作为一种爱好。

func startCamera(){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}

最佳答案

您可以扩展UIViewController,然后您可以通过调用startCamera()在任何UIViewController中访问它。

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

override func viewDidLoad() {
super.viewDidLoad()

if let imagePicker = startCamera() {
imagePicker.delegate = self
}
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// do something
}
}

extension UIViewController {
func startCamera() -> UIImagePickerController? {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
return imagePicker
} else {
return nil
}
}
}

关于swift - 如何从其他类访问相机代码并稍后重用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50651185/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com