使用
PhotoPicker
或 UIImage
时,我无法限制选择器仅显示图像,而不显示视频和 GIF。
struct ImagePickerView: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> UIImagePickerController {
let imagePicker = UIImagePickerController()
imagePicker.delegate = context.coordinator
// Filter to display only images (still includes GIFs)
imagePicker.mediaTypes = [UTType.image.identifier]
return imagePicker
}
func makeCoordinator() -> Coordinator {
return Coordinator()
}
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let selectedImageURL = info[.imageURL] as? URL {
// Check if the selected file is a GIF
if selectedImageURL.pathExtension.lowercased() == "gif" {
print("GIFs are not allowed.")
picker.dismiss(animated: true, completion: nil)
return
}
}
if let selectedImage = info[.originalImage] as? UIImage {
// Process the selected image
print(selectedImage)
}
picker.dismiss(animated: true, completion: nil)
}
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {
}
}
我在 Swift 中使用
UIImagePickerController
来允许用户选择图像,但它仍然显示 GIF。我想完全排除 GIF 在选择器中显示。
我发现GIF在iOS上被归类为图像。
我认为使用选择器不可能做到这一点。
正如其他人在评论中建议的那样,您最好构建自己的照片选择器并使用 Apple 的 PhotoKit 框架获取照片。