第一步:
项目添加以下两个框架
MobileCoreServices.framework
AssetsLibrary.framework
第二步:
在项目的 *****-Bridging-Header.h中导入必要框架(或在swift文件中直接导入 import .....)
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
第三步:在需要调用的viewcontroller文件里添加引用(我的视图是Navigation,所以需要添加UINavigationControllerDelegate)
UIImagePickerControllerDelegate(必须)
UINavigationControllerDelegate(视情况添加)
UIActionSheetDelegate(必须)
第四步:
在imageview响应事件里添加如下方法
var sheet:UIActionSheet
if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)){
sheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "从相册选择","拍照")
}else{
sheet = UIActionSheet(title:nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "从相册选择")
}
sheet.showInView(self.view)
第五步:
添加选择框回调函数,可作为固定写法
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
var sourceType = UIImagePickerControllerSourceType.PhotoLibrary
if(buttonIndex != 0){
if(buttonIndex==1){
//相册
sourceType = UIImagePickerControllerSourceType.PhotoLibrary
}else{
sourceType = UIImagePickerControllerSourceType.Camera
}
let imagePickerController:UIImagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.allowsEditing = true//true为拍照、选择完进入图片编辑模式
imagePickerController.sourceType = sourceType
self.presentViewController(imagePickerController, animated: true, completion: {
})
}
}
第六步:
添加回调函数(固定写法)
func imagePickerControllerDidCancel(picker:UIImagePickerController)
{
self.dismissViewControllerAnimated(true, completion: nil)
}
第七步:
添加回调函数,这个函数是图片完成编辑模式后调用的,处理完的图片在info里(根据需求进行适当更改)
func imagePickerController(picker:UIImagePickerController!, didFinishPickingMediaWithInfo info:NSDictionary)
{
var imageToSave:UIImage
//UIImagePickerControllerEditedImage,这个需要特别注意,根据需要获得不同的图片,此处这个参数代表得到编辑完的图片,还有其他函数QAQ被坑了一晚
imageToSave = info.objectForKey(UIImagePickerControllerEditedImage) as UIImage
//获取到相机拍出来的视频,userImage为我view里的image view控件名称,自行更改
userImage.image=imageToSave
self.dismissViewControllerAnimated(true, completion: nil)
}
初写教程,不足之处还请点出,不胜感激~