遵循代理
@interface RootViewController () <UIActionSheetDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate>
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 200)/2, 100, 200, 200)];
imageView.backgroundColor = [UIColor yellowColor];
imageView.tag = 200;
[self.view addSubview:imageView];
UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
button.frame = CGRectMake((kScreenWidth - 100)/2, imageView.bottom + 40, 100, 40);
[button setTitle:@"点我" forState:(UIControlStateNormal)];
button.backgroundColor = [UIColor blackColor];
[button addTarget:self action:@selector(actionButton:) forControlEvents:(UIControlEventTouchUpInside)];
[self.view addSubview:button];
}
#pragma mark - 点击button触发方法 弹出actionSheet -
- (void)actionButton:(UIButton *)button
{
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
[actionSheet showInView:self.view];
[actionSheet release];
}
#pragma mark ----- ActionSheet触发方法 -----
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
// 调用系统相机
if (buttonIndex == 0)
{
// 如果有系统相机
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
{
UIImagePickerController * picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.allowsEditing = YES;
//摄像头
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
[self presentViewController:picker animated:YES completion:nil];
[picker release];
}
//如果没有系统相机提示用户
else
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"您的设备没有摄像头" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alertView show];
[alertView release];
}
}
// 调用系统相册
if (buttonIndex == 1)
{
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
UIImagePickerController * picker = [[UIImagePickerController alloc]init];
picker.delegate = self;
picker.allowsEditing = YES;//是否可以编辑
//打开相册选择照片
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// 模态进入相册
[self presentViewController:picker animated:YES completion:nil];
[picker release];
}
}
}
#pragma mark - 拍摄完成后或者选择相册完成后自动调用的方法 -
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
// 存入系统相册
// UIImageWriteToSavedPhotosAlbum(backImageView.image, nil, nil, nil);
//得到图片
UIImageView *imageView = (UIImageView *)[self.view viewWithTag:200];
imageView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
// 模态返回
[self dismissViewControllerAnimated:YES completion:nil];
}