gpt4 book ai didi

ios - 如何在 swift 中同时为相机和照片库制作 UIImagePickerController

转载 作者:IT王子 更新时间:2023-10-29 05:02:18 24 4
gpt4 key购买 nike

我使用 UIImagePickerController 通过 iPhone 的相机拍照。

我想同时显示“拍照”和“选择照片”。

我的代码

imagePicker =  UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
//imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)

我尝试同时使用 imagePicker.sourceType = .CameraimagePicker.sourceType = .PhotoLibrary 来执行此操作,但它不起作用...

谢谢

最佳答案

导入 UIImagePickerControllerDelegate 并创建一个变量来分配 UIImagePickerControllervar imagePicker = UIImagePickerController() 并设置 imagePicker.delegate = self

创建一个操作表以显示“相机”和“照片库”的选项。

在您的按钮点击操作上:

@IBAction func buttonOnClick(_ sender: UIButton)
{
self.btnEdit.setTitleColor(UIColor.white, for: .normal)
self.btnEdit.isUserInteractionEnabled = true

let alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { _ in
self.openCamera()
}))

alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { _ in
self.openGallary()
}))

alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))

/*If you want work actionsheet on ipad
then you have to use popoverPresentationController to present the actionsheet,
otherwise app will crash on iPad */
switch UIDevice.current.userInterfaceIdiom {
case .pad:
alert.popoverPresentationController?.sourceView = sender
alert.popoverPresentationController?.sourceRect = sender.bounds
alert.popoverPresentationController?.permittedArrowDirections = .up
default:
break
}

self.present(alert, animated: true, completion: nil)
}


func openCamera()
{
if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerController.SourceType.camera))
{
imagePicker.sourceType = UIImagePickerController.SourceType.camera
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
else
{
let alert = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}

func openGallary()
{
imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}

Swift 下载示例项目, SwiftUI

关于ios - 如何在 swift 中同时为相机和照片库制作 UIImagePickerController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41717115/

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