提问



所以我有一个类似照片库的应用程序,我实现了用户删除图像的能力。这是设置:我有9个UIImageViews,imageView,imageView2等我还有一个编辑按钮和tapGesture动作方法。我将一个Tap Gesture Recognizer拖到我在IB上的视图上,并将它附加到每个UIImageViews。我还将tapGesture动作方法附加到每个UIImageViews。理想情况下,我想要这个方法只有在按下编辑按钮时才会激活。当用户点击编辑,然后点击他们要删除的图片时,我想要显示一个UIAlertView,询问他们是否确定要删除它。这是我正在使用的代码:


- (IBAction)editButtonPressed:(id)sender {
    editButton.hidden = YES;
    backToGalleryButton.hidden = NO;
    tapToDeleteLabel.hidden = NO;
}

- (IBAction)tapGesture:(UITapGestureRecognizer*)gesture
{

    UIAlertView *deleteAlertView = [**UIAlertView alloc] initWithTitle:@"Delete"
                                                              message:@"Are you sure you want to delete this photo?"
                                                             delegate:self
                                                    cancelButtonTitle:@"No"
                                                    otherButtonTitles:@"Yes", nil];
    [deleteAlertView show];

    if (buttonIndex != [alertView cancelButtonIndex]) {

        UIImageView *view = [self.UIImageView];
        if (view) {
            [self.array removeObject:view];
        }


        CGPoint tapLocation = [gesture locationInView: self.view];
        for (UIImageView *imageView in self.view.subviews) {
            if (CGRectContainsPoint(self.UIImageView.frame, tapLocation)) {
                ((UIImageView *)[self.view]).image =nil;
 }

}
        [self.user setObject:self.array forKey:@"images"];
}
}


这段代码显然有很多错误:
使用未声明的标识符按钮索引在此行:if (buttonIndex != [alertView cancelButtonIndex])


在PhotoViewController类型的对象上找不到属性UIImageView这一行UIImageView *view = [self.UIImageView];


此行上的预期标识符((UIImageView *)[self.view]).image =nil;


我对编程很新,我很惊讶我甚至做到了这一点。所以,我只是想弄清楚我需要如何编辑我的代码以便错误消失,并且只要轻触9个图像视图中的一个就可以使用它,并且这样方法只会在首先按下编辑按钮。我之前使用的是标签,效果很好,但是我通过NSData保存图像,所以我不能再使用标签了。非常感谢任何帮助,谢谢!

最佳参考


首先,您不希望将轻击手势附加到图像视图。此外,如果您要拥有超过9个图像,您可能需要滚动视图,或单独处理滚动。首先,删除该手势识别器和所有它的联系。


接下来,确定将用作图库画布的视图类型。一个简单的视图,或ScrollView,或者其他......它现在并不重要,只是为了让它工作。你想要将该视图拖动到你的界面定义中,所以它为视图删除了一个IBOutlet(这样你就可以在代码中引用它了。


您将ImageView放在我刚才提到的视图上。


您可以为手势识别器设置内部标志,但它也有一个可以随时启用/禁用它的属性。因此,您可以非常轻松地使其处于Activity/非Activity状态。


您要做的就是将单个手势识别器放到控制器上,然后将其连接到控制器的实现部分。它将生成用于处理识别器的存根。它将为控制器一般解释点击,并在视图上点击时调用您的代码。


还有一些代码......


在滚动视图中为新图像创建一个框架。


- (CGRect)frameForData:(MyData*)data atIndex:(NSUInteger)idx
{
    CGPoint topLeft;
    int row = idx / 4;
    int col = idx % 4;
    topLeft.x = (col+1)*HORIZ_SPACING + THUMBNAIL_WIDTH * (col);
    topLeft.y = (row+1)*VERT_SPACING + THUMBNAIL_HEIGHT * (row);
    return CGRectMake(topLeft.x, topLeft.y, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
}


为每条元数据和一个小边框创建一个图像视图。


- (UIImageView*)createImageViewFor:(MetaData*)metadata
{
    UIImageView *imageView = [**UIImageView alloc] initWithImage:metadata.lastImage];
    imageView.frame = CGRectMake(0, 0, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);;
    imageView.layer.borderColor = [**UIColor blackColor] CGColor];
    imageView.layer.borderWidth = 2.0;
    imageView.userInteractionEnabled = YES;
    return imageView;
}


这是创建视图并将其添加到父级的位置...


    imageView = [self createImageViewFor:metadata];
    //[data.imageView sizeToFit];

    // Make sure the scrollView contentSize represents the data
    CGRect lastFrame = [self frameForData:data atIndex:self.data.count-1];
    CGFloat newHeight = lastFrame.origin.y + lastFrame.size.height;
    if (self.bookshelfScrollView.contentSize.height < newHeight) {
        CGSize newSize = self.bookshelfScrollView.contentSize;
        newSize.height = newHeight;
        self.bookshelfScrollView.contentSize = newSize;
    }
    [self.bookshelfScrollView addSubview:data.imageView];


因此,您只需创建每个帧,将它们添加到视图中,您唯一需要做的就是在它们上启用用户交互,否则滚动视图不允许手势通过。


好的......看看你发布的代码......因为你没有说出它有什么问题......很难说......下面是你的代码...我的评论是,好吧,评论.. 。


- (IBAction)editButtonPressed:(id)sender {
    editButton.hidden = YES;
    backToGalleryButton.hidden = NO;
    tapToDeleteLabel.hidden = NO;
}
- (IBAction)tapGesture:(UITapGestureRecognizer*)gesture
{
    // I don't think I'd do this here, but it shouldn't cause "problems."
    UIAlertView *deleteAlertView = [**UIAlertView alloc] initWithTitle:@"Delete"
                                                              message:@"Are you sure you want to delete this photo?"
                                                             delegate:self
                                                    cancelButtonTitle:@"No"
                                                    otherButtonTitles:@"Yes", nil];
    [deleteAlertView show];

    // In your controller, you have the main view, which is the view
    // on which you added your UIViews.  You need that view.  Add it as an IBOutlet
    // You should know how to do that...  ctrl-drag to the class INTERFACE source.
    // Assuming you name it "galleryView"

    // Take the tap location from the gesture, and make sure it is in the
    // coordinate space of the view.  Loop through all the imageViews and
    // find the one that contains the point where the finger was taped.
    // Then, "remove" that one from its superview...
    CGPoint tapLocation = [gesture locationInView: self.galleryView];
    for (UIImageView *imageView in self.galleryView.subviews) {
        if (CGRectContainsPoint(imageView.frame, tapLocation)) {
            [imageView removeFromSuperview];
        }
    }
}

其它参考1


就个人而言,在我的小照片库中,我通过用UIButton控件替换UIImageView控件来绕过所有手势识别器的东西,为UIImageView设置按钮的图像属性。 。它看起来完全相同,但是你可以免费获得点击缩略图的功能,根本不需要手势。


所以,我的视图只有UIScrollView,我以编程方式将我的图像添加为按钮,按钮控件的图像设置,例如:


- (void)loadImages
{
    listOfImages = [ImageData newArrayOfImagesForGallery:nil];

    // some variables to control where I put my thumbnails (which happen to be 76 x 76px)

    int const imageWidth = 76;
    int const imageHeight = imageWidth;
    NSInteger imagesPerRow;
    NSInteger imagePadding;
    NSInteger cellWidth;
    NSInteger cellHeight;

    // some variables to keep track of where I am as I load in my images

    int row = 0;
    int column = 0;
    int index = 0;

    // add images to navigation bar

    for (ImageData *item in listOfImages)
    {
        // figure out what row and column I'm on

        imagesPerRow = self.view.frame.size.width / (imageWidth + 2);
        imagePadding = (self.view.frame.size.width - imageWidth*imagesPerRow) / (imagesPerRow + 1);
        cellWidth = imageWidth + imagePadding;
        cellHeight = imageHeight + imagePadding;

        // this is how I happen to grab my UIImage ... this will vary by implementation

        UIImage *thumb = [item imageThumbnail];

        // assuming I found it...

        if (thumb)
        {
            // create my button and put my thumbnail image in it

            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(column * cellWidth  + imagePadding, 
                                      row    * cellHeight + imagePadding, 
                                      imageWidth, 
                                      imageHeight);
            [button setImage:thumb forState:UIControlStateNormal];
            [button addTarget:self
                       action:@selector(buttonClicked:)
             forControlEvents:UIControlEventTouchUpInside];
            button.tag = index++;
            [**button imageView] setContentMode:UIViewContentModeScaleAspectFit];

            // add it to my view

            [scrollView addSubview:button];

            // increment my column (and if necessary row) counters, making my scrollview larger if I need to)

            if (++column == imagesPerRow) 
            {
                column = 0;
                row++;
                [scrollView setContentSize:CGSizeMake(self.view.frame.size.width, (row+1) * cellHeight + imagePadding)];
            }
        }
    }
}

// I also have this in case the user changes orientation, so I'll move my images around if I need to

- (void)rearrangeImages
{
    if (!listOfImages)
    {
        [self loadImages];
        return;
    }

    // a few varibles to keep track of where I am

    int const imageWidth = 76;
    int const imagesPerRow = self.view.frame.size.width / (imageWidth + 2);
    int const imageHeight = imageWidth;
    int const imagePadding = (self.view.frame.size.width - imageWidth*imagesPerRow) / (imagesPerRow + 1);
    int const cellWidth = imageWidth + imagePadding;
    int const cellHeight = imageHeight + imagePadding;

    NSArray *buttons = [**NSArray alloc] initWithArray:[scrollView subviews**];

    int row;
    int column;
    int index;

    CGRect newFrame;

    // iterate through the buttons

    for (UIView *button in buttons)
    {
        index = [button tag];

        if ([button isKindOfClass:[UIButton class**] && index < [listOfImages count])
        {
            // figure out where the button should go

            row = floor(index / imagesPerRow);
            column = index % imagesPerRow;
            newFrame = CGRectMake(column * cellWidth  + imagePadding, 
                                  row    * cellHeight + imagePadding, 
                                  imageWidth, 
                                  imageHeight);

            // if we need to move it, then animation the moving

            if (button.frame.origin.x != newFrame.origin.x || button.frame.origin.y != newFrame.origin.y)
            {
                [UIView animateWithDuration:0.33 animations:^{
                    [button setFrame:newFrame];
                }];
            }
        }
    }

    NSInteger numberOfRows = floor(([listOfImages count] - 1) / imagesPerRow) + 1;

    [scrollView setContentSize:CGSizeMake(self.view.frame.size.width, numberOfRows * cellHeight + imagePadding)];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    [self rearrangeImages];
}


希望这能让您了解如何以编程方式添加UIButton以充当图库中的图像。我已经试着动态编辑这个,所以如果我在这个过程中引入了任何错误,我会提前道歉,但它应该让你了解你可以想象的做什么......我删除了我的代码来做到这一点单独的GCD队列(我这样做是因为我有接近100个图像,并且在主队列上这样做太慢了。)


无论如何,您可以创建buttonClicked方法来显示UIAlertView


- (void)buttonClicked:(UIButton *)sender
{
     if (inEditMode)
     {
         // create your UIAlterView using [sender tag] to know which image you tapped on
     }
}


最后,你UIAlertView上有两个按钮,但你似乎没有看到用户点击的按钮。你的视图控制器应该是UIAlterViewDelegate,你已经定义了你的[[alertView:clickedButtonAtIndex这将执行您的实际编辑步骤。


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
     // ok, will do what I need to do with whatever the user tapped in my alertview
}

其它参考2


我能想到的最简单的事情是默认情况下禁用手势,然后在点击编辑按钮后启用手势。这样,如果图像处于编辑模式,则图像将仅响应轻击手势识别器。