@interface PhotoAppViewController : UIViewController
-(IBAction) getPhoto:(id) sender {
UIImagePickerController * picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if((UIButton *) sender == choosePhotoBtn) {
picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
}
else {
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
[self presentModalViewController:picker animated:YES];
}
首先創(chuàng)建一個新的 UIImagePickerController 對象系吩。它是一個視圖控制器纲菌,可以按任意視圖控制器方式正常顯示出來(顯示于導航視圖番官,加載于表格視圖,呈現(xiàn)為模型視圖控制器等)冶匹。然后,設置代理為我們的視圖控制器。它表示當用戶選取照片時挪丢,拾取器將調用類中的某個方法狈谊。接著喜命,確定哪個按鈕被按下。由于兩個按鈕都連接到此方法上河劝,我們需要確定到底哪個被按下壁榕。到底是顯示照相機圖片還是顯示照片庫圖片是由拾取器的一個屬性決定的,看看代碼就會很清楚赎瞎。最后牌里,調用presentModalViewController。它將使拾取器以動畫的形式從屏幕底向上移動务甥,切換到視圖牡辽。根據(jù)按下的按鈕的不同,你將看到下面圖像:
一旦選擇了照片敞临,ImagePicker 將回調 didFinishPickingMediaWithInfo态辛。在視圖控制器中加入下列代碼:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissModalViewControllerAnimated:YES];
imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
}
第一行代碼是隱藏拾取器。隨后將圖像視圖的 image 屬性設置為返回的圖像挺尿。拾取器返回一個 NSDictionary 對象奏黑。這是由于 UIImagePickerControllerMediaType 將指示返回的是視頻還是圖像。