1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| import UIKit
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate { var uploadAlertController : UIAlertController? var pick:UIImagePickerController? var imageV :UIImageView? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.gray imageV = UIImageView.init(frame: CGRect.init(x: 30, y: 300, width: 80, height: 80)) self.view.addSubview(imageV!) initAlertController() tapImage() } func initAlertController() { weak var blockSelf = self uploadAlertController = UIAlertController(title:nil, message: nil, preferredStyle:UIAlertControllerStyle.actionSheet) let takePhoto = UIAlertAction(title:"拍照", style:UIAlertActionStyle.default) { (action:UIAlertAction)in blockSelf?.actionAction(action: action) } let photoLib = UIAlertAction(title:"从相册选择", style:UIAlertActionStyle.default) { (action:UIAlertAction)in blockSelf?.actionAction(action: action) } let cancel = UIAlertAction(title:"取消", style:UIAlertActionStyle.cancel) { (action:UIAlertAction)in blockSelf?.actionAction(action: action) } uploadAlertController?.addAction(takePhoto) uploadAlertController?.addAction(photoLib) uploadAlertController?.addAction(cancel) } func tapImage(){ present(uploadAlertController!, animated:true, completion: nil) initImagePickerController() } func initImagePickerController() { pick = UIImagePickerController() pick?.delegate = self pick?.allowsEditing = true } func actionAction(action:UIAlertAction) { if action.title == "拍照" { self.getImageFromCamera(type: .camera) }else if action.title == "从相册选择" || action.title == "更换头像" { self.getImageFromPhotoLib(type: .photoLibrary) } } func getImageFromCamera(type:UIImagePickerControllerSourceType) { pick?.sourceType = type self.present(pick!, animated: true, completion:nil) } func getImageFromPhotoLib(type:UIImagePickerControllerSourceType) { pick?.sourceType = type self.present(pick!, animated: true, completion:nil) } func imagePickerController(_ picker:UIImagePickerController, didFinishPickingMediaWithInfo info: [String :Any]){ let type:String = (info[UIImagePickerControllerMediaType]as!String) if type == "public.image" { let img = info[UIImagePickerControllerOriginalImage]as?UIImage imageV?.image = img } picker.dismiss(animated:true, completion:nil) } func imagePickerControllerDidCancel(_ picker:UIImagePickerController){ picker.dismiss(animated:true, completion:nil) } }
|