【问题标题】:How to call UICollectionViewCell ImageView in IBAction Method?如何在 IBAction 方法中调用 UICollectionViewCell ImageView?
【发布时间】:2014-04-29 12:15:55
【问题描述】:

我正在努力解决一些可能很容易但我无法做到的事情!

我在 UICollectionViewCell 内有一个 UIImageView,在 UICollectionView 外有一个按钮。在我的按钮的 IBAction 方法中,如何调用这个 UIImageView?

cell.ImageView 是不允许的。

编辑代码:

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

return 1;

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

return 10;

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

static NSString *cellIdentifier = @"Cell";
VestimentaDetailCell *cell = (VestimentaDetailCell *) [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

[cell.activityIndicator startAnimating];

cell.imageFile.image = [UIImage imageNamed:@"LoadLook.png"];

PFFile *imageFile = [self.vestimenta objectForKey:[NSString stringWithFormat:@"image_%ld", (long)indexPath.row]];

[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error && data.length > 0) {

cell.imageFile.image = [UIImage imageWithData:data];

    UITapGestureRecognizer *infoLook = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];

    infoLook.numberOfTapsRequired = 1;

    [cell.imageFile addGestureRecognizer:infoLook];

} else {

    [cell.progressView removeFromSuperview];

        }

} progressBlock:^(int percentDone) {
    float percent = percentDone * 0.02;
    [cell.progressView setProgress:percent];
    if (percentDone == 100){
        [cell.progressView removeFromSuperview];
    };

    [cell.activityIndicator stopAnimating];
}];

return cell;
}

动作方法:

-(void)handleTap:(UITapGestureRecognizer *) infoLook{

if ([sender isSelected]) {
    [sender setImage:[UIImage imageNamed:@"Like.png"] forState:UIControlStateNormal];
    [sender setSelected:NO];
} else {
    [sender setImage:[UIImage imageNamed:@"Liked.png"] forState:UIControlStateSelected];
    [sender setSelected:YES];
UIImageView *like = [[UIImageView alloc] initWithFrame:CGRectMake(120, 220, 100, 100)];
like.image = [UIImage imageNamed:@"Love.png"];
[self.view addSubview:like];
[UIView animateWithDuration:2 animations:^{like.alpha = 0.0;}];

这部分是我不能调用UICollectionViewCell的UIImageView的地方:

    NSData* data = UIImageJPEGRepresentation(cell.imageFile.image, 0.8f);
    PFFile *likedImage = [PFFile fileWithName:@"Image.jpg" data:data];

    [likedImage saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (!error) {
            PFObject *userLikes = [PFObject objectWithClassName:@"UserProfile"];
            [userLikes setObject:likedImage forKey:@"likedLook"];

            userLikes.ACL = [PFACL ACLWithUser:[PFUser currentUser]];

            PFUser *user = [PFUser currentUser];
            [userLikes setObject:user forKey:@"user"];

            [userLikes saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (!error) {
                    NSLog(@"Saved");
                } else {
                    NSLog(@"Error: %@%@", error, [error userInfo]);
                }
            }];
        }
    }];

NSLog(@"Liked Image");

}

}

【问题讨论】:

  • 你能更详细地解释一下“调用 UIImageView”是什么意思吗?这不是正确的术语。
  • 如果我想更改位于 UICollectionViewCell 内的 UIImageView 的图像,我将如何在 IBAction 方法中设置我的代码?在这种方法中..我怎么能告诉它改变图像 cell.imageFile 是不允许的,因为它不会识别什么是单元格。
  • 你没有。您不应该尝试访问单元格中的图像视图,而应该访问用于填充单元格的基础数据。您应该有一个数组,其中包含用于填充图像视图的图像(或图像名称)。
  • 点击按钮后,我想更改图像。
  • 您希望每个单元格中的所有图像都相同吗?如果不是,您如何确定要更改哪个单元格?

标签: ios uiimageview uicollectionviewcell ibaction


【解决方案1】:

首先你必须通过使用方法获取项目的索引路径

NSIndexPath *indexpath=[NSIndexPath indexPathForItem:<#(NSInteger)#> inSection:<#(NSInteger)#>];

只需在此方法中提供行号和节号。 然后使用该索引路径使用以下方法获取单元格

UICollectionViewCell *cell = [collectionView1 cellForItemAtIndexPath:indexPath];

然后你就可以访问单元格的属性了。

【讨论】:

  • 谢谢!通过这种方法,indexPath 给我一个未声明标识符的错误,建议我将其更改为 NSIndexPath,如果我这样做,则会出现错误:Unexpected interface name 'NSIndexPath: expected expression.
  • 您可以使用方法NSIndexPath *indexpath=[NSIndexPath indexPathForItem:&lt;#(NSInteger)#&gt; inSection:&lt;#(NSInteger)#&gt;] 获取索引路径,您需要提供您打算与之交互的单元格的行号和节号。请参考我编辑的答案。
  • 在使用此过程时,只需确保在对单元格进行任何更改之前检查 nil 值。根据cellForItemAtIndexPath : 方法的文档The cell object at the corresponding index path or nil if the cell is not visible or indexPath is out of range.
  • 如果我想在所有 10 个单元格中设置这个怎么办?我已经更新了我的代码。如果可以,请查看它。
  • 然后您可以对每个项目使用此过程。当然在检查单元格是否为零之后
【解决方案2】:

现在您已将按钮作为单元格的一部分,您可以执行以下操作:

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    // ... your code here for cellForItemAtIndexPath: method
    likeButton.tag = indexPath.row;
    [cell.likeButton addTarget:self action:@selector(liked:) forControlEvents:UIControlEventTouchUpInside];
}

- (void) liked:(UIButton *)button {
    UIImage *image = [imageArray objectAtIndex:button.tag];
    NSData* data = UIImageJPEGRepresentation(image, 0.8f);
    PFFile *likedImage = [PFFile fileWithName:@"Image.jpg" data:data];

    [likedImage saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (!error) {
            PFObject *userLikes = [PFObject objectWithClassName:@"UserProfile"];
            [userLikes setObject:likedImage forKey:@"likedLook"];

            userLikes.ACL = [PFACL ACLWithUser:[PFUser currentUser]];

            PFUser *user = [PFUser currentUser];
            [userLikes setObject:user forKey:@"user"];

            [userLikes saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (!error) {
                    NSLog(@"Saved");
                } else {
                    NSLog(@"Error: %@%@", error, [error userInfo]);
                }
            }];
        }
    }];
}

虽然有这个想法,但尚未经过测试。

始终首选从填充您的集合视图的数组(例如您通过索引访问的图像或字符串数​​组)操作/检索数据,而不是访问其单元格。

【讨论】:

  • 我实际上在单元格类中移动了动作。解决它。不管怎么说,还是要谢谢你!现在我遇到了一个字符串问题,将发布另一个问题。
【解决方案3】:

试试这个:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView1 cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
        UICollectionViewCell *cell=[collectionView1 dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
        cell.backgroundView = [[UIImageView alloc] initWithImage:@"image.jpg"];
        cell.backgroundView.contentMode = UIViewContentModeScaleAspectFit;
        cell.backgroundColor=[UIColor blackColor];

        return cell;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [your_image_array count];
}

检测所选图像:

  - (void)collectionView:(UICollectionView *)collectionView
    didSelectItemAtIndexPath:(NSIndexPath *)indexPath
    {
        NSLog(@"Selected Image = %d",indexPath.row);
    }

【讨论】:

    【解决方案4】:
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
            tapGesture.numberOfTapsRequired = 1;
    imgView.tag=indexPath.row
    [imgView setUserInteractionEnabled:YES];
            [imgView addGestureRecognizer:tapGesture];
    
    
        - (void)handleSingleTap:(UITapGestureRecognizer *)tap
    {
        NSLog(@"%d",[tap view].tag);
    }
    

    【讨论】:

      【解决方案5】:

      你可以创建一个属性

      @property(strong, nonatomic) UIImage *imageForCell;
      

      然后用第一张图片初始化它

      - (void)viewDidLoad {
          [super viewDidLoad];
          self.imageForCell = [UIImage imageNamed:@"myImage.png"];
      }
      

      在您的按钮中,您应该先更改图像,然后重新加载特定单元格(在本例中为单元格 5):

      - (IBAction)buttonTapped:(id)sender {
          self.imageForCell = [UIImage imageNamed:@"newImage.png"];
          NSIndexPath indexPath = [NSIndexPath indexPathForRow:5 inSection:0];
          [self.myCollectionView reloadItemsAtIndexPaths:indexPath];
      }
      

      填充单元格时使用属性 imageForCell:

      -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
          ...
          cell.imageFile.image = self.imageForCell;
          ...
      }
      

      【讨论】:

        【解决方案6】:

        对于任何需要帮助的人,这就是我所做的:

        为单元创建一个类。

        在 Cell Class 实现文件中发布代码。 就我而言:

        #import "VestimentaDetailCell.h"
        
        @implementation VestimentaDetailCell
        
        @synthesize imageFile, progressView;
        
        - (id)initWithFrame:(CGRect)frame
        {
        self = [super initWithFrame:frame];
        if (self) {
            // Initialization code
        }
        return self;
        }
        
        - (IBAction)likeLook:(id)sender {
        
            if ([sender isSelected]) {
                [sender setImage:[UIImage imageNamed:@"Like.png"] forState:UIControlStateNormal];
                [sender setSelected:NO];
        
            } else {
                [sender setImage:[UIImage imageNamed:@"Liked.png"] forState:UIControlStateSelected];
                [sender setSelected:YES];
        
                UIImageView *like = [[UIImageView alloc] initWithFrame:CGRectMake(120, 220, 100, 100)];
                like.image = [UIImage imageNamed:@"Love.png"];
                [self addSubview:like];
                [UIView animateWithDuration:2 animations:^{like.alpha = 0.0;}];
        
                NSData *imageData = UIImageJPEGRepresentation(imageFile.image, 1);
                [self uploadImage:imageData];
        
                NSLog(@"Liked Image");
        
        }
        }
        
        -(void)uploadImage:(NSData *)imageData {
        
            PFFile *likedImage = [PFFile fileWithName:@"Image.jpg" data:imageData];
        
            [likedImage saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (!error) {
                    PFObject *userLikedPhoto = [PFObject objectWithClassName:@"UserLikedPhoto"];
                    [userLikedPhoto setObject:likedImage forKey:@"likedLook"];
        
                    userLikedPhoto.ACL = [PFACL ACLWithUser:[PFUser currentUser]];
        
                    PFUser *user = [PFUser currentUser];
                    [userLikedPhoto setObject:user forKey:@"User"];
        
                    [userLikedPhoto saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (!error) {
                            NSLog(@"Saved");
                        } else {
                            NSLog(@"Error: %@%@", error, [error userInfo]);
                        }
                    }];
                } else {
                    NSLog(@"Error: %@%@", error, [error userInfo]);
                }
            }];
        }
        
        @end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-10-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多