最新消息:关注【太平洋学习网】微信公众号,可以获取全套资料,【全套Java基础27天】【JavaEE就业视频4个月】【Android就业视频4个月】

使用UIActionSheet弹出相册和拍照功能案例

IOS 太平洋学习网 浏览 评论

UIActionSheet是处理ios弹出按钮的类,下面我们将使用uialertsheet来实现app的拍照和相册选择功能,先看看UIActionSheet功能实现后的效果,如图。

QQ20170905-171134.png

实现步骤:

1:首先在需要在info.plist内添加手机相册和拍照的权限,添加这两行。

Privacy - Photo Library Usage Description //相册
Privacy - Camera Usage Description //拍照

如图这样添加。

QQ20170905-171730.png

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
�

完毕!

来源网站:太平洋学习网,转载请注明出处:http://www.tpyyes.com/a/object-c_ios/204.html
"文章很值,打赏犒劳作者一下"
微信号: Javaweb_engineer

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

与本文相关的文章

发表我的评论
取消评论

表情

您的回复是我们的动力!

  • 昵称 (必填)

网友最新评论