2个UIButtons设置2个UIImageViews

时间:2013-04-18 19:41:37

标签: ios objective-c uiimageview uibutton

我有2 UIButton个,我想要两个按钮来挑选图片,button1正在将图片设置为imageview1button2设置为imageView2 。我现在创建了button1,用于选择图片并将imageView1设置为该图片,但如果我正在创建button2,我现在不需要做以下事情:

- (IBAction)chooseImage1:(id)sender {
     imagePicker.delegate = self;
     imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
     [self presentViewController:imagePicker animated:YES completion:nil];
}

- (IBAction)chooseImage2:(id)sender {
     imagePicker.delegate = self;
     imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
     [self presentViewController:imagePicker animated:YES completion:nil];
}

UIImage *image;

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

      NSURL *mediaURL;
      mediaURL = (NSURL *)[info valueForKey:UIImagePickerControllerMediaURL];
      image = (UIImage *)[info valueForKey:UIImagePickerControllerOriginalImage];

     imageView1.image=image;
     [picker dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
     [picker dismissViewControllerAnimated:YES completion:nil];
}

1 个答案:

答案 0 :(得分:1)

.h文件中创建索引。像

这样的东西
NSUInteger *selectedImageIndex;

.m文件中:

- (void)showImagePicker:(UIImagePickerControllerSourceType)source{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = source;
    ipc.allowsEditing = YES;
    ipc.delegate = self;
    [self presentModalViewController:ipc animated:YES];
}

- (IBAction)chooseImage1:(id)sender {
    selectedImageIndex = 1;
    [self showImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (IBAction)chooseImage2:(id)sender {
    selectedImageIndex = 2;
    [self showImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
}    

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
        UIImage *img = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        if (!img)
           img = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

        if (selectedImageIndex == 1)
           imageView1.image=img;
        else
           imageView2.image = img;

        [picker dismissViewControllerAnimated:YES completion:nil];
}


-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
       [picker dismissViewControllerAnimated:YES completion:nil];
}

但话说回来,这只是一种方法。