继昨天的实作练习,有相机,会执行以下的程序码:
let vc = UIImagePickerController()
vc.sourceType = .camera // 相簿
vc.delegate = self
vc.allowsEditing = true
present(vc, animated: true)
到这边会报错是正常的,因为没给它 UIImagePickerControllerDelegate
因此在专案里用 extension 去写委任
extension MainVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
// 显示 photo
guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {return}
imageView.image = image
picker.dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
附上完整程序码
import UIKit
class MainVC: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var takePhoto: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.setNavigationBarHidden(true, animated: false) // 隐藏指示条
}
@IBAction func didTapButton(btn: UIButton) {
let vc = UIImagePickerController()
if !UIImagePickerController.isSourceTypeAvailable(.camera) {
let alertController = UIAlertController(title: "ERROR", message: "Device has no camera.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Alright", style: .default, handler: { (alert: UIAlertAction!) in
})
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
print("ERROR:没有相机功能!")
}
else { vc.sourceType = .camera }
vc.delegate = self
present(vc, animated: true)
}
}
extension MainVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
picker.dismiss(animated: true, completion: nil)
// 显示 photo
guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {return}
imageView.image = image
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
为了测试和使用相机,您必须使用真正的连接设备,若烧在模拟器,会报错:Source type 1 not available
这样就完成从相簿选取照片的实作了!明天会分享从相簿选取照片( 有裁剪照片功能 ),敬请期待!
<<: [ 卡卡 DAY 25 ] - React Native 手机装置 keyboard 问题之 右下角的 next and go 设定
>>: Swift纯Code之旅 Day30. 「新增闹钟功能(最终章) - 分手快乐」
cookie的使用方法: 这边我们用setcookie() 添加COOKIE值 setcookie(...
实作自己的全域 count, setCount codesandbox demo const { c...
import pandas as pd from sklearn.preprocessing imp...
上一篇我们学到怎麽使用Vim,还有修改commit message,这次要做的事情呢,就是要来合并跟...
前言 相信大家看完上一篇之後,对於HTTP有一个基本的认识了,从这篇开始会介绍一些跟HTTP相关名字...