将UIImage放置在UITableViewCell中的tapped图像上

时间:2013-09-18 20:32:30

标签: ios objective-c uitableview uiimage

目前我有自定义UITablViewCell(BIDSelectBusinessCustomCell),它们显示在tableView(myTableView)中。自定义单元格由UIImageView和标签组成。加载视图时,标签将填充我的模型中的字符串。 UIImageViews是空白的。我希望用户能够“点击”UIImageView,从手机上存储的内容中选择一张图片,并将该图像保存到UIImageView。

从下面的代码我可以得到'tap'手势,然后弹出pickercontroller并且用户选择一个图像。现在代码的方式是为所有UIImageViews设置一个选定的图像。这是可以理解的。但我希望将它设置为特定的UIImageView并且不知道如何。

代码:

#import <UIKit/UIKit.h>

@interface BIDBusinessSelectViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (strong, nonatomic) NSArray *linkedBusinessParseArray;
//Stores the array of models
@property (strong, nonatomic) NSMutableArray *linkedBusinessParseModelArray;
@property NSUInteger relevantIndex;
@property (strong, nonatomic) UIImage *tempImageHolder;

@end

#import "BIDBusinessSelectViewController.h"
#import <Parse/Parse.h>
#import "BIDBusinessModel.h"
#import "BIDSelectBusinessCustomCell.h"

@interface BIDBusinessSelectViewController () <ImageSelect>
{
    BIDSelectBusinessCustomCell *aCell;//define a cell of ur custom cell to hold selected cell
    UIImage *choosenImage; //image to set the selected image
}
@end

@implementation BIDBusinessSelectViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;

    self.linkedBusinessParseModelArray = [[NSMutableArray alloc]init];

    //create query
    PFQuery *linkedBusinessParseQuery = [PFQuery queryWithClassName:@"linkedBusinessParseClass"];
    //follow relationship
    [linkedBusinessParseQuery whereKey:@"currentBusinessUserParse" equalTo:[PFUser currentUser]];
    [linkedBusinessParseQuery whereKey:@"linkRequestSentParse" equalTo:@"Approved"];
    [linkedBusinessParseQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        self.linkedBusinessParseArray = objects; //store them in my model array
        //loop through model array from Parse
        for (NSDictionary *dict in self.linkedBusinessParseArray) {
            NSString *descPlaceNameParse = [dict objectForKey:@"placeDescriptionParse"];
            NSLog(@"descPlacesNameParse: %@",descPlaceNameParse);
            PFObject *tempObj = (PFObject *) dict;
            NSString *tempObjString = tempObj.objectId;
            NSLog(@"tempObjString (inside dict): %@", tempObjString);

            //storing values from Parse into my model
            BIDBusinessModel *userModel = [[BIDBusinessModel alloc]init];
            userModel.descriptionModelParse = descPlaceNameParse;
            userModel.objectIdModelParse = tempObjString;
            [self.linkedBusinessParseModelArray addObject:userModel];
            NSLog(@"self.linkedBusinessParseModelArray: %lu", (unsigned long)[self.linkedBusinessParseModelArray count]);
            //Reload tableview. Has to go here in block otherwise it does not occur
            [self.myTableView reloadData];

        }

    }];


    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                              message:@"Device has no camera"
                                                             delegate:nil
                                                    cancelButtonTitle:@"OK"
                                                    otherButtonTitles: nil];

        [myAlertView show];

    }

    choosenImage = [UIImage imageNamed:@"pin.png"]; //hear u need to set the image for cell assuming that u are setting initially same image for all the cell


}

#pragma mark -
#pragma mark Table Delegate Methods

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.linkedBusinessParseModelArray.count; //returns count of model NSMutableArray
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Start cellforRowStIndex");
    static NSString *CellIdentifier = @"Cell";
    BIDSelectBusinessCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[BIDSelectBusinessCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    BIDBusinessModel *bizModel;
    bizModel = self.linkedBusinessParseModelArray[indexPath.row];
    bizModel.image = choosenImage;
    //cell.descLabel.text = [NSString stringWithFormat:@"bid= %d",indexPath.row];//set text from the model//Omitted for my desc
    cell.descLabel.text = bizModel.descriptionModelParse;

    cell.logoImage.image =bizModel.image; //setting the image initially the image when u set in "viewDidLoad" method from second time onwords it will set from the picker delegate method
    //insted of settig the gesture hear set it on the custom cell
    cell.ImageSelectDelegate = self; //setting the delegate
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

// hear implementation of delegate method

- (void)selectSetImageForSelectedLogImage:(UIImageView *)logoImgView;
{
    //open up the image picker
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    aCell = (BIDSelectBusinessCustomCell *)logoImgView.superview; //her getting the cell

    [self presentViewController:picker animated:YES completion:NULL];


}


-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *aChosenImage = info[UIImagePickerControllerEditedImage];
    //UIImage holder to transfer to cellForRowAtIndexPath
    choosenImage = aChosenImage;
    NSIndexPath *indexPath = [self.myTableView indexPathForCell:aCell];

    [self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; //hear reloading the selected cell only not entire tableview
    //get the model and set the choosen image
    BIDBusinessModel *bizModel;
    bizModel = self.linkedBusinessParseModelArray[indexPath.row];
    bizModel.image = aChosenImage;


    [picker dismissViewControllerAnimated:YES completion:NULL];
}

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

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

#import <UIKit/UIKit.h>

@protocol ImageSelect<NSObject> //for this u need use custom delegate so i did like this
- (void)selectSetImageForSelectedLogImage:(UIImageView *)logoImgView;
@end


@interface BIDSelectBusinessCustomCell : UITableViewCell
@property (strong, nonatomic) IBOutlet UILabel *descLabel;
@property (strong, nonatomic) IBOutlet UIImageView *logoImage;
@property (nonatomic, assign) id<ImageSelect>ImageSelectDelegate; // deleagte

@end

#import "BIDSelectBusinessCustomCell.h"

@implementation BIDSelectBusinessCustomCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.logoImage = [[UIImageView alloc]init];
        self.descLabel = [[UILabel alloc]init];
        //set up gesture hear in the custom cell insted in the controller class
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLogoImage:)];
        [tap setNumberOfTouchesRequired:1];
        [tap setNumberOfTapsRequired:1];
        [tap setDelegate:self];
        self.logoImage.userInteractionEnabled = YES;
        [self.logoImage addGestureRecognizer:tap];

        //[self addSubview:logoImage];
        //[self addSubview:descLabel];

    }
    return self;}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)tapLogoImage:(UITapGestureRecognizer *)guesture
{
    if([self.ImageSelectDelegate respondsToSelector:@selector(selectSetImageForSelectedLogImage:)])
    {
        [self.ImageSelectDelegate selectSetImageForSelectedLogImage:self.logoImage];//call the delegate method from the selected cell
    }

}

@end

2 个答案:

答案 0 :(得分:0)

对于这个,我试过但最后我做了类似的事情,通过这个你可能会找到一些解决方案。并希望这有助于你:)

  //in custom cell "BIDSelectBusinessCustomCell.h"
  #import <UIKit/UIKit.h>
   //define a delegate method that is called each time when u tapped on cell 
  @protocol ImageSelect<NSObject> //for this u need use custom delegate so i did like this
  - (void)selectSetImageForSelectedLogImage:(UIImageView *)logoImgView;
  @end

  @interface BIDSelectBusinessCustomCell : UITableViewCell <UIImagePickerControllerDelegate,UINavigationControllerDelegate> 
{
   UIImageView *logoImage; //your image holder 
   UILabel *descLabel;     //label
}
@property (nonatomic, retain) UIImageView *logoImage;
@property (nonatomic, retain) UILabel *descLabel;
@property (nonatomic, assign) id<ImageSelect>ImageSelectDelegate; // deleagte

@end

  //in custom cell "BIDSelectBusinessCustomCell.m"
 #import "BIDSelectBusinessCustomCell.h"

 @implementation BIDSelectBusinessCustomCell 
 @synthesize logoImage;
 @synthesize descLabel;
 @synthesize ImageSelectDelegate;

 - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
 {
     self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
     if (self) {
     // Initialization code
     logoImage = [[UIImageView alloc]init];
     descLabel = [[UILabel alloc]init];
    //set up gesture hear in the custom cell insted in the controller class
     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLogoImage:)];
     [tap setNumberOfTouchesRequired:1];
     [tap setNumberOfTapsRequired:1];
     [tap setDelegate:self];
     logoImage.userInteractionEnabled = YES;
     [logoImage addGestureRecognizer:tap];

     [self addSubview:logoImage];
     [self addSubview:descLabel];

   }
  return self;
}

 - (void)dealloc
{

 [logoImage release];
 [descLabel release];
 [super dealloc];
}


 - (void)setSelected:(BOOL)selected animated:(BOOL)animated
 {
    [super setSelected:selected animated:animated];

   // Configure the view for the selected state
 }

 - (void)layoutSubviews
  {
    //in this method simply i am setting the frames of subviews 
   [super layoutSubviews];
   self.logoImage.frame = CGRectMake(130, 2, 44,44 );
   self.descLabel.frame = CGRectMake(20, 2, 60, 44);

 }

 - (void)tapLogoImage:(UITapGestureRecognizer *)guesture
{
    if([self.ImageSelectDelegate respondsToSelector:@selector(selectSetImageForSelectedLogImage:)])
   {
      [self.ImageSelectDelegate selectSetImageForSelectedLogImage:self.logoImage];//call the delegate method from the selected cell 
   }

}

@end

 //in your view controller class u need to do something like this ;)
 //ViewController.h file
 #import <UIKit/UIKit.h>

 @interface ViewController : UIViewController
 @property (retain, nonatomic) IBOutlet UITableView *aTableView;
 @property (nonatomic, retain) NSIndexPath *selectedIndexPath; //no need just try
 @end 

 //in your "ViewController.m" file

  @interface ViewController ()<UITableViewDataSource, UITableViewDelegate,UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControll erDelegate,ImageSelect>//delegate
{
    BIDSelectBusinessCustomCell *aCell;//define a cell of ur custom cell to hold selected cell
    UIImage *choosenImage; //image to set the selected image
}

- (void)viewDidLoad
{
   [super viewDidLoad];
   choosenImage = [UIImage imageNamed:@"Star.png"]; //hear u need to set the image for cell assuming that u are setting initially same image for all the cell 


}

 - (void)didReceiveMemoryWarning
  {  
      [super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.
  }




  - (void)dealloc {
  [aTableView release];

   [super dealloc];
  }


 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  {


       return 1;
  }

  - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
 {

   return 4; //pass array check array contains valid objects
 }





    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {

  BIDSelectBusinessCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil)
    {
       cell = [[BIDSelectBusinessCustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
     BIDBusinessModel *bizModel;
    bizModel = self.linkedBusinessParseModelArray[indexPath.row];
    bizModel.image = aChosenImage;
   cell.descLabel.text = [NSString stringWithFormat:@"bid= %d",indexPath.row];//set text from the model


   cell.logoImage.image =bizModel.image; //setting the image initially the image when u set in "viewDidLoad" method from second time onwords it will set from the picker delegate method 
    //insted of settig the gesture hear set it on the custom cell 
    cell.ImageSelectDelegate = self; //setting the delegate
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
   return cell;

}

 // hear implementation of delegate method

 - (void)selectSetImageForSelectedLogImage:(UIImageView *)logoImgView;
{
   //open up the image picker
   UIImagePickerController *picker = [[UIImagePickerController alloc]init];
   picker.delegate = self;
   picker.allowsEditing = YES;
   picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
   aCell = (BIDSelectBusinessCustomCell *)logoImgView.superview; //her getting the cell 

   [self presentViewController:picker animated:YES completion:NULL];


}

  -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
 {
   UIImage *aChosenImage = info[UIImagePickerControllerEditedImage];
   //UIImage holder to transfer to cellForRowAtIndexPath
   choosenImage = aChosenImage;
   NSIndexPath *indexPath = [aTableView indexPathForCell:aCell];

   [self.aTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; //hear reloading the selected cell only not entire tableview
   //get the model and set the choosen image
    BIDBusinessModel *bizModel;
    bizModel = self.linkedBusinessParseModelArray[indexPath.row];
    bizModel.image = aChosenImage;


  [picker dismissViewControllerAnimated:YES completion:NULL];
}


答案 1 :(得分:0)

是的,这会将图像设置为每一行..

现在你能做的是: -

加载tableViewCells时只需将UIImageView的标记指定为(indexPath.Row)。

这会为ImageView分配唯一标签。 您可以在点击时轻松获取该imageView的标记,现在您可以通过该imageView的tagValue将图像指定给特定的imageView。

这会将图像分配给特定的imageView,因为它们都有唯一的标记。

希望你能得到问题的答案。