缩放UIscrollview使图像子视图消失

时间:2013-08-12 12:52:04

标签: iphone ios6 uiscrollview zooming

我搜索过很多但无法找到合适的解决方案(google或stackoverflow)。从3天开始真的感到沮丧和挣扎:

1。 我的主要动机是创建一个像iPad图库一样的屏幕。图像来自服务器,可以是5或50或100的数字。我已经按照ray wenderlich的教程并逐步完成了它(http://www.raywenderlich.com/10518/how-to-use-uiscrollview-to-scroll-and-zoom-content)。但仍然面临着这个问题。

2。 我有一个主滚动视图(外部)我想要这些图像,以便我可以使用滚动(和分页)功能放大/缩小每个图像,当我双击图像时,它应该缩放到2倍和第二次加倍它应该恢复正常。

3。 为此,我有一个内部滚动视图,将为每个图像保存UIImageview。这样每个图像都可以放大/缩小。但是当我加载图像时,我只能看到第一张图像,而其他图像则不会显示。当我设置每个滚动视图的背景颜色和图像视图时我也知道问题与他们有关但我无法弄清楚它是什么:

我需要什么: 1.我的代码中的问题在哪里,我在互联网上搜索了很多但是无法弄清楚,我曾经尝试了很多其他样本。 2.如果任何正文可以修改代码或者可以给我正确的代码示例,这可以使我的代码工作。

下面是我的代码

.h文件

    #import <UIKit/UIKit.h>


@interface SliderViewController : UIViewController<UIScrollViewDelegate,MFMailComposeViewControllerDelegate,UIPrintInteractionControllerDelegate,UIAlertViewDelegate,UIPopoverControllerDelegate,ButtonPressedDelegate>
{

    NSMutableArray *thumbsArray;
    int index;
    int count;
    UIView *containerView;
    bool isEmpty;
    NSString *firstName;
    NSString *lastName;
    NSMutableArray *annotatedThumbsArray;
}


@property(nonatomic,retain) NSMutableArray *thumbsArray;
@property(nonatomic, assign) int index;
@property(nonatomic, assign) int count;
@property(nonatomic,retain) NSString *firstName;
@property(nonatomic,retain) NSString *lastName;
@property(nonatomic,retain) NSMutableArray *annotatedThumbsArray;
@property(nonatomic,retain) UIPopoverController *popover_controller;

@property(nonatomic,retain) IBOutlet UIScrollView *scrollView;
@property(nonatomic,retain) IBOutlet UIPageControl *pageControl;

@end

.m文件:

#import "SliderViewController.h"

#import "AppDelegate.h"

#define VIEW_FOR_ZOOM_TAG (10)

@interface SliderViewController ()
{
    UITapGestureRecognizer *singleFingerTap;
    CGRect rect;
}
    @property (nonatomic, strong) NSMutableArray *pageImages;
    @property (nonatomic, strong) NSMutableArray *pageViews;

    - (void)loadVisiblePages;
    - (void)loadPage:(NSInteger)page;
    - (void)purgePage:(NSInteger)page;

@end

implementation SliderViewController
@synthesize pageImages,pageControl,libid,libname,thumbsArray,index,count,imageNameLabel,imageNameView,footerView,navBar,firstName,lastName,annotatedThumbsArray;
@synthesize drawingViewController,popover_controller;

@synthesize pageViews = _pageViews;
@synthesize scrollView = _scrollView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


#pragma mark - view cycle
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLog(@"THUMBSSSSS%@",thumbsArray);
    pageImages = [[NSMutableArray alloc]init];
    isEmpty = false;

    self.scrollView.backgroundColor = [UIColor greenColor];



    NSInteger pageCount = self.thumbsArray.count;

    // Set up the page control
    self.pageControl.currentPage = index;
    self.pageControl.numberOfPages = pageCount;

    // Set up the array to hold the views for each page
    _pageViews = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < pageCount; ++i)
    {
        [_pageViews addObject:[NSNull null]];
    }

    self.navBar.topItem.title = [NSString stringWithFormat:@"%@ %@",self.firstName,self.lastName];

    singleFingerTap =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(viewTapped:)];
    [self.view addGestureRecognizer:singleFingerTap];

    rect = CGRectZero;

}

- (void)centerScrollViewContents
{
    CGSize boundsSize = self.scrollView.bounds.size;
    CGRect contentsFrame = [self.scrollView viewWithTag:202].frame;

    if (contentsFrame.size.width < boundsSize.width) {
        contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
    } else {
        contentsFrame.origin.x = 0.0f;
    }

    if (contentsFrame.size.height < boundsSize.height)
    {
        contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
    }
    else
    {
        contentsFrame.origin.y = 0.0f;
    }

    [self.scrollView viewWithTag:202].frame = contentsFrame;
}


-(void)setViewContents
{
    // Set up the content size of the scroll view
    CGSize pagesScrollViewSize = self.scrollView.frame.size;
    self.scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * self.thumbsArray.count, pagesScrollViewSize.height);
    [self.scrollView setContentOffset:CGPointMake(index*pagesScrollViewSize.width, 0.0f)];
    self.scrollView.delegate = self;

    self.navBar.topItem.title = [NSString stringWithFormat:@"%@ %@",firstName,lastName];

    // Load the initial set of pages that are on screen
    [self loadVisiblePages];

    [self centerScrollViewContents];
}

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



    [self setViewContents];
    [self performSelectorOnMainThread:@selector(showHeaderFooterViews) withObject:nil waitUntilDone:YES];
}
- (void)loadVisiblePages
{
        // First, determine which page is currently visible
        CGFloat pageWidth = self.scrollView.frame.size.width;
        NSInteger page = (NSInteger)floor((self.scrollView.contentOffset.x * 2.0f + pageWidth) / (pageWidth * 2.0f));

        // Update the page control
        self.pageControl.currentPage = page;

        // Work out which pages you want to load
        isEmpty = false;
        NSInteger firstPage = page - 1;
        NSInteger lastPage = page + 1;

        // Purge anything before the first page
        for (NSInteger i=0; i<firstPage; i++) {
            [self purgePage:i];
        }
        for (NSInteger i=firstPage; i<=lastPage; i++) {
            [self loadPage:i];
        }
        for (NSInteger i=lastPage+1; i<self.thumbsArray.count; i++) {
            [self purgePage:i];
        }

        thumbnail *tempThumb = [[thumbnail alloc]init];
        tempThumb = [thumbsArray objectAtIndex:page];
        NSString *image_name = [[NSString alloc]initWithFormat:@"%@",tempThumb.name];
        tempThumb = nil;
        [self.imageNameLabel setText:[NSString stringWithFormat:@"%@(%d/%d)",image_name,pageControl.currentPage+1,pageControl.numberOfPages]];
}


-(void)purgePage:(NSInteger)page
{
        if(page < 0 || page >= self.thumbsArray.count+self.annotatedThumbsArray.count)
        {
            // If it's outside the range of what you have to display, then do nothing
            return;
        }

        // Remove a page from the scroll view and reset the container array
        UIView *pageView = [_pageViews objectAtIndex:page];
        if ((NSNull*)pageView != [NSNull null])
        {
            [pageView removeFromSuperview];
            [_pageViews replaceObjectAtIndex:page withObject:[NSNull null]];
        }
}

- (void)loadPage:(NSInteger)page
{
    @try
    {
        if (page < 0 || page >= self.thumbsArray.count)
        {
            // If it's outside the range of what we have to display, then do nothing
            return;
        }

        // Load an individual page, first checking if you've already loaded it
        UIView *pageView = [_pageViews objectAtIndex:page]; // page views holds


        if ((NSNull*)pageView == [NSNull null] || isEmpty)
        {
            CGRect frame = self.scrollView.bounds;
            frame.origin.x = frame.size.width * page;
            frame.origin.y = 0.0f;
            frame = CGRectInset(frame, 10.0f, 0.0f);

            thumbnail *tempThumb = [[thumbnail alloc]init];
            tempThumb = [thumbsArray objectAtIndex:page];
            NSString *image_name = [[NSString alloc]initWithFormat:@"%@",tempThumb.name];
            tempThumb = nil;

            NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
            NSString *documentDir = [path objectAtIndex:0];
            NSString *docsPath = [documentDir stringByAppendingPathComponent:[NSString stringWithFormat:@"downloaded/%@",libid]];
            UIImage *fullImage = [[UIImage alloc]init];
            NSString *imagePath;

            if(page<(thumbsArray.count-annotatedThumbsArray.count))
            {
                imagePath = [docsPath stringByAppendingPathComponent:image_name];
            }
            else
            {
                documentDir = [documentDir stringByAppendingPathComponent:libid];
                imagePath = [documentDir stringByAppendingPathComponent:image_name];
            }
            BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:imagePath];
            if(fileExists)
            {
                NSLog(@"file NAMEEEE: - %@",image_name);
                fullImage = [UIImage imageWithContentsOfFile:imagePath];
            }
            else
            {
                NSLog(@"FILE NOT FOUND");
                fullImage = [UIImage imageNamed:@"noimage.jpg"];
                isEmpty = true;
            }

            UIImageView *newPageView = [[UIImageView alloc] initWithImage:fullImage];
            [newPageView setUserInteractionEnabled:YES];
            newPageView.contentMode = UIViewContentModeScaleAspectFit;
            newPageView.frame = frame;
            newPageView.backgroundColor = [UIColor blueColor];
            newPageView.tag = VIEW_FOR_ZOOM_TAG;

            // ******* add each image view into a scroll view so that it can be zoomed and also can be swiped
            UIScrollView *pageScrollView = [[UIScrollView alloc] initWithFrame:frame];
            pageScrollView.tag = 202;
            pageScrollView.minimumZoomScale = 1.0f;
            pageScrollView.maximumZoomScale = 2.0f;
            pageScrollView.zoomScale = 1.0f;
//            pageScrollView.contentSize = newPageView.bounds.size;
            pageScrollView.delegate = self;
            pageScrollView.showsHorizontalScrollIndicator = NO;
            pageScrollView.showsVerticalScrollIndicator = NO;
            pageScrollView.backgroundColor = [UIColor yellowColor];

            [self.scrollView addSubview:pageScrollView];
            [pageScrollView addSubview:newPageView];
            [self.scrollView bringSubviewToFront:pageScrollView];

            NSLog(@"frame --> %f", frame.origin.x);
            NSLog(@"frame --> %f", newPageView.frame.origin.x);
            NSLog(@"frame --> %f", pageScrollView.frame.origin.x);

            [self.pageViews replaceObjectAtIndex:page withObject:newPageView];

            UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewDoubleTapped:)];
            doubleTapRecognizer.numberOfTapsRequired = 2;
            doubleTapRecognizer.numberOfTouchesRequired = 1;
            [newPageView addGestureRecognizer:doubleTapRecognizer];

        }

    }
    @catch (NSException *exception)
    {
        NSLog(@"crash in - loadPage = %@", exception);
    }
    @finally {
//        NSLog(@"finally-");
    }
}
#pragma mark - double tapped

-(void)viewDoubleTapped:(UITapGestureRecognizer*)recognizer
{
   //TODO: code for 2x zooming in / out 
}

#pragma mrak - view tapped
-(void) viewTapped:(UITapGestureRecognizer*)recognizer
{
    if([self.footerView isHidden])
    {
        [self performSelectorOnMainThread:@selector(showHeaderFooterViews) withObject:nil waitUntilDone:YES];
    }
}
- (void)showHeaderFooterViews
{
    [self.imageNameView setHidden:NO];
    [self.footerView setHidden:NO];

    [self performSelector:@selector(hideHeaderFooterViews) withObject:nil afterDelay:5.0];

}

- (void)hideHeaderFooterViews
{
    NSLog(@"hide header footer called ");
    [self.imageNameView setHidden:YES];
    [self.footerView setHidden:YES];
}



#pragma mark - back button (cross button ) pressed

- (IBAction)backButtonPressed:(id)sender
{
    @try
    {
        AppDelegate* myAppDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

        int l = [[[myAppDelegate window].rootViewController childViewControllers] count];// to access the previous controller

        FolderViewController *parentVC = (FolderViewController *)((UITabBarController *)[[[myAppDelegate window].rootViewController childViewControllers] objectAtIndex:l-2]); // accessing FolderviewC
        [parentVC loadThumbnails];


        [self.view removeFromSuperview];
        [self removeFromParentViewController];
    }
    @catch (NSException *exception) {
        NSLog(@"crash in SliderVC: backButtonPressed - %@", exception);
    }
    @finally {

    }
}


#pragma  mark - scroll view delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // Load the pages that are now on screen
    [self loadVisiblePages];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    if(scrollView.tag == 202)
        return [scrollView viewWithTag:VIEW_FOR_ZOOM_TAG];

    return nil;
}


- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    NSLog(@"view zoomed");
    [self centerScrollViewContents ];
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
    NSLog(@"Beginning zooming");
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale{
    NSLog(@"Zooming Did End");
}

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

- (IBAction)swipeRight:(id)sender
{
    if (!((self.scrollView.contentOffset.x+self.scrollView.frame.size.width) >= self.scrollView.contentSize.width))
    {
        [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x+self.scrollView.frame.size.width, self.scrollView.contentOffset.y)];
        [self loadVisiblePages];
    }
}

- (IBAction)swipeLeft:(id)sender
{
    if (!((self.scrollView.contentOffset.x-self.scrollView.frame.size.width) < 0))
    {
        [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x-self.scrollView.frame.size.width, self.scrollView.contentOffset.y)];
        [self loadVisiblePages];
    }
}

注意:我保存了我从Documents目录中的服务器获取的图像,并从loadPage:方法访问它们(这是访问这些图像的正确位置吗?)

非常感谢任何帮助。非常感谢你们。

0 个答案:

没有答案
相关问题