在Swift 4中使用UIImagePickerController可以通过以下步骤:
import UIKit
。UIImagePickerController()
初始化一个UIImagePickerController对象。imagePickerController.delegate = self
。imagePickerController.sourceType = .photoLibrary
。present(imagePickerController, animated: true, completion: nil)
。imagePickerController(_:didFinishPickingMediaWithInfo:)
和imagePickerControllerDidCancel(_:)
。在imagePickerController(_:didFinishPickingMediaWithInfo:)
方法中,可以获取用户选择的图片,并进行后续处理。以下是一个完整的示例代码:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let imagePickerController = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
imagePickerController.delegate = self
imagePickerController.sourceType = .photoLibrary
}
@IBAction func selectImage(_ sender: UIButton) {
present(imagePickerController, animated: true, completion: nil)
}
// UIImagePickerControllerDelegate methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let selectedImage = info[.originalImage] as? UIImage {
// 处理选择的图片
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
}
这是一个简单的示例,演示了如何在Swift 4中使用UIImagePickerController选择图片。你可以根据自己的需求进行进一步的处理和扩展。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云