最近始めたiOSプログラミングのコードのことも備忘録として、はたまたツッコミを乞うためとして書いていきたいと思います。
特にソーシャル系iPhoneアプリでよく使う写真を選ぶアレのコードです。何かボタンを押すと下からウニョンと出てきてカメラかライブラリかの選択肢を選ぶやつ。あれ、ActionSheetと呼ぶらしいです。
てなわけで、細かく分けて以下を実装してみました。
- ActionSheetというかUIActionSheetを表示
- ライブラリ、カメラそれぞれのケースを実装。といってもUIImagePickerControllerにお任せ
- 選択した写真をUIImageViewに表示
こういうUIがあったとして。
implementation部分のコードはこんな感じになりました。正直ARCまだよくわかってナス。
ViewController.m
- (IBAction)showActionSheet:(id)sender {
UIActionSheet *actionSheet = [[UIActionSheet alloc]init];
[actionSheet setDelegate:self];
[actionSheet setTitle:@"写真を選びます"];
[actionSheet addButtonWithTitle:@"ライブラリから選択"];
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
[actionSheet addButtonWithTitle:@"カメラで撮影"];
[actionSheet setCancelButtonIndex:2];
}else{
[actionSheet setCancelButtonIndex:1];
}
[actionSheet addButtonWithTitle:@"キャンセル"];
[actionSheet showFromToolbar:toolbar];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
[imagePicker setDelegate:self];
switch (buttonIndex) {
case 0:
[imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentModalViewController:imagePicker animated:YES];
break;
case 1:
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentModalViewController:imagePicker animated:YES];
break;
default:
break;
}
}
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
[imageView setImage:image];
[self dismissModalViewControllerAnimated:YES];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
[self dismissModalViewControllerAnimated:YES];
}
カメラ無しデバイスのことを考慮しているのがポイント。あと気づいたのは、デリゲートされるdidFinishPickingImageってのではUIImageがそのまま渡されるんですぐ利用できて便利っす。実機で動かしてみてActionSheetで選択→「ライブラリ表示またはカメラ起動」がやたら遅い気がするのは気のせいかなぁ。
というわけで参考になるかわかりませんが「写真を選ぶアレ」のコードでした。間違ったところがあればツッコミください。
最近、参考にしてる本
iOSプログラミング 第2版
posted with amazlet at 12.01.28
アーロン・ヒレガス ジョー・コンウェイ Aaron Hillegass Joe Conway
ピアソン桐原
売り上げランキング: 11341
ピアソン桐原
売り上げランキング: 11341
