UIActionSheet是处理ios弹出按钮的类,下面我们将使用uialertsheet来实现app的拍照和相册选择功能,先看看UIActionSheet功能实现后的效果,如图。
实现步骤:
1:首先在需要在info.plist内添加手机相册和拍照的权限,添加这两行。
Privacy - Photo Library Usage Description //相册 Privacy - Camera Usage Description //拍照
如图这样添加。
2:在界面添加一个button按钮,并实现UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate这三个代理类。
3:给button添加一个事件,本人是拉线的,然后使用UIActionSheet实现图上面的功能,代码如下。
�#import "ViewController.h" @interface ViewController ()<UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate> @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } //点击按钮,弹出UIActionSheet提示框 - (IBAction)showUIActionSheet:(UIButton *)sender { UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"添加图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册" , @"拍照", nil]; [actionSheet showInView:self.view]; } #pragma mark - UIActionSheetDelegate 代理方法,点击里面的按钮会设置不同的源 - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { if (2 == buttonIndex) { return; } [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //显示图片的控制器 UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init]; [imgPicker.view setBackgroundColor:[UIColor clearColor]]; [imgPicker setDelegate:self]; if (0 == buttonIndex) { //设置相册源 [imgPicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; } else if (1 == buttonIndex) { //模拟器不能使用相机,会报错,只能真机使用 [imgPicker setSourceType:UIImagePickerControllerSourceTypeCamera]; } [self presentViewController:imgPicker animated:YES completion:nil]; }]; } #pragma mark - UIImagePickerControllerDelegate 代理方法 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [picker dismissViewControllerAnimated:YES completion:nil]; } //图片选中之后的回调方法,也是代理方法 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info { [self dismissViewControllerAnimated:YES completion:nil]; //获取相册或拍照的图片对象selectedImg UIImage *selectedImg = info[UIImagePickerControllerOriginalImage]; //对图片对象进行操作... } @end �
完毕!