2012-01-30 62 views
0

在我的項目中,我使用UIIamgepickercontroller從庫中選擇圖像並將其加載到UIImageView中。我爲2張圖像做了這樣的工作,所以每個圖像視圖都有兩個按鈕,但我不想爲圖像選取器複製兩次代碼,而且我不確定如何實現以便該方法知道要加載哪個圖像視圖圖像進入。我想我需要使用按鈕標籤?但找不到正確的方法。如何共享2個按鈕的UIImagepickercontroller代碼

這裏是我的代碼:

.H

`#import <UIKit/UIKit.h> 
#import <Foundation/Foundation.h> 

@interface LoadViewController : UIViewController <UINavigationControllerDelegate, UIImagePickerControllerDelegate> { 
    IBOutlet UIImageView *imageView; 
    IBOutlet UIImageView *imageView2; 
} 

- (IBAction)pick1; 
- (IBAction)pick2; 
- (void) getImage; 


@end` 

.M

#import "LoadViewController.h" 

@implementation LoadViewController 

UIImage *imageHandle; 

- (IBAction)pick2 { 

    [self getImage]; 
    imageView2.image = imageHandle; 
} 

- (IBAction)pick1{ 

    [self getImage]; 
    imageView.image = imageHandle; 
} 

- (void)getImage { 
     UIImagePickerController *picker = [[UIImagePickerController alloc] init]; 
     picker.delegate = self; 
     picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; 
     [self presentModalViewController:picker animated:YES]; 

} 


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo { 
    imageHandle = image; 
    [picker.parentViewController dismissModalViewControllerAnimated:YES]; 

} 

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { 
    [picker.parentViewController dismissModalViewControllerAnimated:YES]; 
} 

@end 

心中已經一直有另一個問題是方法要跟我是否選擇了圖像或取消了視圖似乎沒有工作,雖然如果我註釋掉整個方法(void)imagePickerControllerDidCancel那麼它將取消?!?

我在學習這個東西的初期階段,任何幫助將非常感激!

感謝

回答

1

您可以使用標籤標識按鈕,這是一個任意整數(你可以在Interface Builder中設置此)。問題是你拒絕了接收發件人引用的機會(按鈕);而不是- (IBAction)pick1,比如- (IBAction)pick1:(id)sender。現在您可以檢查發件人的tag(將發件人轉換爲UIView *,以便編譯器理解您在做什麼)。

+0

非常感謝您的幫助。 – Matt104 2012-01-31 22:40:24