How to randomize images in a page scrollview - ios

I have 12 images, stored in an array...
I use this to output the image.
scrollView = [[UIScrollView alloc] init];
CGRect scrollFrame;
scrollFrame.origin.x = 0;
scrollFrame.origin.y = 0;
scrollFrame.size.width = WIDTH_OF_SCROLL_PAGE;
scrollFrame.size.height = HEIGHT_OF_SCROLL_PAGE;
scrollView = [[UIScrollView alloc] initWithFrame:scrollFrame];
scrollView.bounces = YES;
scrollView.pagingEnabled = YES;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.delegate = self;
scrollView.userInteractionEnabled = YES;
NSMutableArray *slideImages = [[NSMutableArray alloc] init];
[slideImages addObject:#"KODAK1.png"];
[slideImages addObject:#"KODAK2.png"];
[slideImages addObject:#"KODAK3.png"];
[slideImages addObject:#"KODAK4.png"];
[slideImages addObject:#"KODAK5.png"];
[slideImages addObject:#"KODAK6.png"];
[slideImages addObject:#"KODAK7.png"];
[slideImages addObject:#"KODAK8.png"];
[slideImages addObject:#"KODAK9.png"];
[slideImages addObject:#"KODAK10.png"];
[slideImages addObject:#"KODAK11.png"];
[slideImages addObject:#"KODAK12.png"];
srandom(time(NULL));
int x = arc4random() % 12;
for ( int i = 0 ;i<[slideImages count]; i++) {
//loop this bit
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[slideImages objectAtIndex:i]]];
imageView.frame = CGRectMake((WIDTH_OF_IMAGE * i) + LEFT_EDGE_OFSET, 0 , WIDTH_OF_IMAGE, HEIGHT_OF_IMAGE);
[scrollView addSubview:imageView];
[imageView release];
}
[scrollView setContentSize:CGSizeMake(WIDTH_OF_SCROLL_PAGE * ([slideImages count] +0), HEIGHT_OF_IMAGE)];
[scrollView setContentOffset:CGPointMake(0, 0)];
[self.view addSubview:scrollView];
[self.scrollView scrollRectToVisible:CGRectMake(WIDTH_OF_IMAGE,0,WIDTH_OF_IMAGE,HEIGHT_OF_IMAGE) animated:YES];
[super viewDidLoad]
How can i output random images in the UIView? as in there are 12 images, but each time i run the application, the app will start at a random image, but i will still be able to scroll through the images. i hope you guys understand my question.

You could "shuffle" the NSMutableArray each time you create it:
NSMutableArray *slideImages = [[NSMutableArray alloc] init];
...
[slideImages shuffle];
...
So each time you will be initializing the UIScrollView with a different order.
shuffle is not part of the SDK. For an sample implementation, please have a look to this:
#implementation NSMutableArray (Shuffling)
- (void)shuffle
{
static BOOL seeded = NO;
if(!seeded)
{
seeded = YES;
srandom(time(NULL));
}
NSUInteger count = [self count];
for (NSUInteger i = 0; i < count; ++i) {
// Select a random element between i and end of array to swap with.
int nElements = count - i;
int n = (random() % nElements) + i;
[self exchangeObjectAtIndex:i withObjectAtIndex:n];
}
}
#end
Import the header file containing you category declaration:
#interface NSMutableArray (Shuffling)
- (void)shuffle;
#end
wherever you want to use shuffle.

Related

Nested UIScrollView not paging for Internal UIScrollView

I am trying to build a screen which has 2 UIScrollViews, 1 Main Scroll View which is used as a container and to scroll vertically (this is working fine).
Inside the Main Scroll View, is a second scroll view, which is used for display different images. This needs to be scrolled horizontally so it will page to other images which will also update content details displayed in the Main Scroll View.
When attempting to get these two features to work together, the paging functionality does not work, however if it is outside the main scroll view it will work but will not scroll with the rest of the content.
The Image Scroll View is being detected in the events as well, but doesn't show any ability to scroll.
Below are my 3 functions which are performing the work.
- (void)viewDidLoad
{
[super viewDidLoad];
// Set up the Image Scroll View
ImageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, screenWidth, homeImage)];
ImageScrollView.scrollEnabled = YES;
ImageScrollView.userInteractionEnabled=YES;
[ImageScrollView setPagingEnabled:YES];
[ImageScrollView setAlwaysBounceVertical:NO];
ImageScrollView.delegate = self;
// Set up the image array
NSArray *imagesArray = [NSArray arrayWithObjects:#"staff1big.png", #"staff2big.png", #"staff3big.png", nil];
// Create each image subview
for (int i = 0; i < [imagesArray count]; i++)
{
CGFloat xOrigin = i * ImageScrollView.frame.size.width;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, ImageScrollView.frame.size.width, ImageScrollView.frame.size.height)];
[imageView setImage:[UIImage imageNamed:[imagesArray objectAtIndex:i]]];
[ImageScrollView addSubview:imageView];
}
// Set the Content Size and Offset
[ImageScrollView setContentSize:CGSizeMake(ImageScrollView.frame.size.width * [imagesArray count], ImageScrollView.frame.size.height)];
[ImageScrollView setContentOffset:CGPointMake(screenWidth*currentIndex, 0)];
// Get the staff object
dataSource = [DataSource dataSource];
NSArray *staffArray = [dataSource getStaff];
// Setup the Pager Control
self.pageControl = [[UIPageControl alloc] init];
NSInteger placement = (screenWidth/2)-50;
self.pageControl.frame = CGRectMake(placement, homeImage-30, 100, 20);
self.pageControl.numberOfPages = [staffArray count];
self.pageControl.currentPage = currentIndex;
[self setStaff:staffArray[currentIndex]];
// Add the Main Scroll View
MainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
MainScrollView.delegate = self;
MainScrollView.scrollEnabled = YES;
MainScrollView.userInteractionEnabled=YES;
// Add each object to the correct scroll view
[ImageScrollView addSubview:self.pageControl];
[MainScrollView addSubview:ImageScrollView];
[MainScrollView addSubview:lineView];
[self setDisplayContent]; // note the MainScrollView is added to the self.view in this method along with setting the content size to screenWidth and height is determine by the generated content.
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat pageWidth = ImageScrollView.frame.size.width;
float fractionalPage = ImageScrollView.contentOffset.x / pageWidth;
NSInteger page = lround(fractionalPage);
currentIndex = page;
self.pageControl.currentPage = page;
[self displayContent];
}
- (void)displayContent
{
int i = currentIndex;
if (i < 0)
{
i = 0;
} else if (i > 2) {
i = 2;
}
[self setStaff:allStaff[i]];
// remove all from view
for(UIView *subview in [MainScrollView subviews]) {
[subview removeFromSuperview];
}
NSArray *imagesArray = [NSArray arrayWithObjects:#"staff1big.png", #"staff2big.png", #"staff3big.png", nil];
for (int i = 0; i < [imagesArray count]; i++)
{
CGFloat xOrigin = i * ImageScrollView.frame.size.width;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, ImageScrollView.frame.size.width, ImageScrollView.frame.size.height)];
[imageView setImage:[UIImage imageNamed:[imagesArray objectAtIndex:i]]];
[ImageScrollView addSubview:imageView];
}
[ImageScrollView setContentSize:CGSizeMake(ImageScrollView.frame.size.width * [imagesArray count], ImageScrollView.frame.size.height)];
[ImageScrollView setContentOffset:CGPointMake(screenWidth*currentIndex, 0)];
// Get the staff
dataSource = [DataSource dataSource];
NSArray *staffArray = [dataSource getStaff];
self.pageControl = [[UIPageControl alloc] init];
NSInteger placement = (screenWidth/2) - 50;
self.pageControl.frame = CGRectMake(placement, homeImage-30, 100, 20);
self.pageControl.numberOfPages = [staffArray count];
self.pageControl.currentPage = currentIndex;
[self setStaff:staffArray[currentIndex]];
[ImageScrollView addSubview:self.pageControl];
[MainScrollView addSubview:ImageScrollView];
[MainScrollView addSubview:lineView];
[self setDisplayContent];
}
I do need to refactor some of the code to make more efficient, but at this stage I am just trying to get the horizontal paging to scroll horizontally.
If anyone would possibly be able to help point me in the right direction as to how to fix this issue, it would be greatly appreciated.
Here is a visual of the UI that I am trying to keep but have the image scroll horizontal.
Staff Display

UIpagecontrol Need Animation Rigth to Left

Using UIControlpage in my application. load the image and display in page control successfully. but i want to display the images animation like right to left move. Using timer call page control and increase the array count.
//// using NSTimer to call function to show the animation.
[NSTimer scheduledTimerWithTimeInterval:5.0
target:self
selector:#selector(loadNextController)
userInfo:nil
repeats:YES];
ScrollViewPage = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20, frameX, frameY)];
ScrollViewPage.pagingEnabled = YES;
ScrollViewPage.backgroundColor=[UIColor redColor];
ScrollViewPage.delegate = self;
ScrollViewPage.backgroundColor = [UIColor clearColor];
ScrollViewPage.contentSize = CGSizeMake(frameX, frameY);
ScrollViewPage.showsHorizontalScrollIndicator = NO;
ScrollViewPage.pagingEnabled = YES;
pageControl = [[UIPageControl alloc] init];
pageControl.frame = CGRectMake(100,self.view.frame.size.height-100,self.view.frame.size.width-200,100);
pageControl.numberOfPages = [_pageImages count];
pageControl.currentPage = 0;
[self.view addSubview: ScrollViewPage];
for(int i = 0; i < [_pageImages count]; i++)
{
NSURL *url = [NSURL URLWithString:[_pageImages objectAtIndex:i]];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *tmpImage = [UIImage imageWithData:data];
_backgroundImageView = [[UIImageView alloc] initWithImage:tmpImage];
_backgroundImageView.frame = CGRectMake(frameX * i, 0.0, frameX, frameY);
[ScrollViewPage addSubview:_backgroundImageView];
}
ScrollViewPage.contentSize = CGSizeMake(frameX*[_pageImages count], frameY);
pageControl.backgroundColor=[UIColor orangeColor];
[self.view addSubview:pageControl];
[pageControl addTarget:self action:#selector(pageTurn:) forControlEvents:UIControlEventValueChanged];
///// Here call the timer function
- (void)loadNextController
{
pageControl.currentPage = (pageControl.currentPage+1)%self.pageImages.count;
ScrollViewPage.contentOffset = CGPointMake(pageControl.currentPage * self.view.bounds.size.width, 0);
}
Here i need to show left to right move in uipagecontrol. help me..
In general you should always write what is your current result, what is the expected result and what have you tried.
I can only guess the issue you are facing is there are no animations.
The scroll view has a method setContentOffset:animated which you can use to animate the transition. Another approach is to use UIView animateWithDuration and sett the offset in the method block.
Try any or both of these...
[ScrollViewPage setContentOffset:CGPointMake(pageControl.currentPage * self.view.bounds.size.width, 0) animated:YES];
Or
[UIView animateWithDuration:0.2 animations:^{
ScrollViewPage.contentOffset = CGPointMake(pageControl.currentPage * self.view.bounds.size.width, 0);
}];
EDIT: Loop images.
To loop images you really only need 2 images on the scroll view at the time. I will show you the concept with 3 and you can try and play around with it.
NSArray *allImages;
NSInteger currentIndex = 0;
UIScrollView *scrollView;
UIImageView *imageViews[3];
- (void)begin {
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width*3.0, scrollView.frame.size.height); // always have 3 images at the time
scrollView.contentOffset = CGPointMake(scrollView.frame.size.width, 0.0); // put to center
for(int i=0; i<3; i++) {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(scrollView.frame.size.width*i, 0.0, scrollView.frame.size.width, scrollView.frame.size.height)];
[scrollView addSubview:imageView];
imageView[i] = imageView;
}
[self layoutForIndex:currentIndex];
}
- (void)nextImage {
currentIndex++;
[self layoutForIndex:currentIndex];
scrollView.contentOffset = CGPointZero;
[scrollView setContentOffset:CGPointMake(scrollView.frame.size.width, 0.0) animated:YES]
}
- (void)layoutForIndex:(NSInteger)index {
if(allImages.count > 0) { // we need at least one image to do something
for(int i=0; i<3; i++) {
// do the circling
NSInteger imageIndex = index-1+i;
while(imageIndex < 0) imageIndex+=allImages.count;
while(imageIndex >= allImages.count) imageIndex-=allImages.count;
imageViews[i].image = imageViews[imageIndex];
}
}
}
But in general for what you are doing you do not even need a scroll view. On next you can simply add another image view next to the current one and then use the UIView animation to reposition both of the image views.

UIViewControllers in ContentView of UIScrollView?

I don't want to use page control because i have to change the button when the user scroll horizontally.
So I am using UIScrollview and container view.
By following this tutorial
I am able to add child view controller in container view but the scroll view does not scroll with auto layout.
Here is my code
- (void)viewDidLoad {
[super viewDidLoad];
self.array_pageContent = [[NSMutableArray alloc] init];
CallViewController *objGameReviewPageContentViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"CallViewController"];
[self addChildViewController:objGameReviewPageContentViewController];
UIView * view = objGameReviewPageContentViewController.view;
HomeViewController *objHomeViewController= [self.storyboard instantiateViewControllerWithIdentifier:#"HomeViewController"];
[self addChildViewController:objHomeViewController];
UIView * view1 = objHomeViewController.view;
GroupViewController *objGroupViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"GroupViewController"];
[self addChildViewController:objGroupViewController];
UIView * view2 = objGroupViewController.view;
CallenderViewController *objCallenderViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"CallenderViewController"];
[self addChildViewController:objCallenderViewController];
UIView * view3 = objGroupViewController.view;
CasesViewController *objCasesViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"CasesViewController"];
[self addChildViewController:objCasesViewController];
UIView * view4 = objGroupViewController.view;
[self.scrollViewContent setPagingEnabled:YES];
[self.scrollViewContent setScrollEnabled:YES];
[self.scrollViewContent setShowsHorizontalScrollIndicator:YES];
[self.scrollViewContent setShowsVerticalScrollIndicator:NO];
[self.scrollViewContent setDelegate:self];
[self.array_pageContent addObject:view];
[self.array_pageContent addObject:view1];
[self.array_pageContent addObject:view2];
[self.array_pageContent addObject:view3];
[self.array_pageContent addObject:view4];
NSInteger pageCount = self.array_pageContent.count;
self.pageControl.currentPage = 0;
self.pageControl.numberOfPages = pageCount;
self.mutableArray_pageContentViews = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < pageCount; ++i) {
[self.mutableArray_pageContentViews addObject:[NSNull null]];
}
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
CGSize pagesScrollViewSize = self.scrollViewContent.frame.size;
self.scrollViewContent.contentSize = CGSizeMake(pagesScrollViewSize.width * self.array_pageContent.count, pagesScrollViewSize.height);
[self loadVisiblePages];
}
- (void)loadPage:(NSInteger)page {
if (page < 0 || page >= self.array_pageContent.count) {
return;
}
UIView *pageView = [self.mutableArray_pageContentViews objectAtIndex:page];
if ((NSNull*)pageView == [NSNull null]) {
CGRect frame = self.scrollViewContent.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0.0f;
UIView *newPageView = nil;
newPageView = [self.array_pageContent objectAtIndex:page];
newPageView.frame = frame;
[self.scrollViewContent addSubview:newPageView];
[self.mutableArray_pageContentViews replaceObjectAtIndex:page withObject:newPageView];
}
}
- (void)purgePage:(NSInteger)page {
if (page < 0 || page >= self.array_pageContent.count) {
return;
}
UIView *pageView = [self.mutableArray_pageContentViews objectAtIndex:page];
if ((NSNull*)pageView != [NSNull null]) {
[pageView removeFromSuperview];
[self.mutableArray_pageContentViews replaceObjectAtIndex:page withObject:[NSNull null]];
}
}
- (void)loadVisiblePages {
CGFloat pageWidth = self.scrollViewContent.frame.size.width;
NSInteger page = (NSInteger)floor((self.scrollViewContent.contentOffset.x * 2.0f + pageWidth) / (pageWidth * 2.0f));
self.pageControl.currentPage = page;
NSInteger firstPage = page - 1;
NSInteger lastPage = page + 1;
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.array_pageContent.count; i++) {
[self purgePage:i];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[self loadVisiblePages];
}
And the hierarchy for storyboard is
Remove Container View From Views hierarchy your scroll will be work.
and replcae your viewDidLoad() metod from following code.
- (void)viewDidLoad {
[super viewDidLoad];
CGFloat width = 0.0;
self.array_pageContent = [[NSMutableArray alloc] init];
CallViewController *objGameReviewPageContentViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"CallViewController"];
[self addChildViewController:objGameReviewPageContentViewController];
width = objGameReviewPageContentViewController.view.frame.size.width;
[self.scrollViewContent addSubview:objGameReviewPageContentViewController.view];
// UIView * view = objGameReviewPageContentViewController.view;
HomeViewController *objHomeViewController= [self.storyboard instantiateViewControllerWithIdentifier:#"HomeViewController"];
CGRect frame = objHomeViewController.view.frame;
frame.origin.x = objGameReviewPageContentViewController.view.frame.size.width;
objHomeViewController.view.frame = frame;
width += frame.size.width;
NSLog(#"%f",width);
[self addChildViewController:objHomeViewController];
[self.scrollViewContent addSubview:objHomeViewController.view];
// UIView * view1 = objHomeViewController.view;
GroupViewController *objGroupViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"GroupViewController"];
frame = objGroupViewController.view.frame;
frame.origin.x = objGameReviewPageContentViewController.view.frame.size.width*2;
objGroupViewController.view.frame = frame;
width += frame.size.width;
NSLog(#"%f",width);
[self addChildViewController:objGroupViewController];
[self.scrollViewContent addSubview:objGroupViewController.view];
// [self addChildViewController:objGroupViewController];
// UIView * view2 = objGroupViewController.view;
CallenderViewController *objCallenderViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"CallenderViewController"];
frame = objCallenderViewController.view.frame;
frame.origin.x = objGameReviewPageContentViewController.view.frame.size.width*3;
objCallenderViewController.view.frame = frame;
width += frame.size.width;
NSLog(#"%f",width);
[self addChildViewController:objCallenderViewController];
[self.scrollViewContent addSubview:objCallenderViewController.view];
// [self addChildViewController:objCallenderViewController];
// UIView * view3 = objGroupViewController.view;
CasesViewController *objCasesViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"CasesViewController"];
frame = objCasesViewController.view.frame;
frame.origin.x = objGameReviewPageContentViewController.view.frame.size.width*4;
objCasesViewController.view.frame = frame;
width += frame.size.width;
NSLog(#"%f",width);
[self addChildViewController:objCasesViewController];
[self.scrollViewContent addSubview:objCasesViewController.view];
// [self addChildViewController:objCasesViewController];
// UIView * view4 = objGroupViewController.view;
[self.scrollViewContent setPagingEnabled:YES];
[self.scrollViewContent setScrollEnabled:YES];
[self.scrollViewContent setShowsHorizontalScrollIndicator:YES];
[self.scrollViewContent setShowsVerticalScrollIndicator:NO];
[self.scrollViewContent setDelegate:self];
self.scrollViewContent.contentSize = CGSizeMake(width, self.scrollViewContent.frame.size.height);
// [self.array_pageContent addObject:view];
// [self.array_pageContent addObject:view1];
// [self.array_pageContent addObject:view2];
// [self.array_pageContent addObject:view3];
// [self.array_pageContent addObject:view4];
// NSInteger pageCount = self.array_pageContent.count;
//
// self.pageControl.currentPage = 0;
// self.pageControl.numberOfPages = pageCount;
//
// self.mutableArray_pageContentViews = [[NSMutableArray alloc] init];
// for (NSInteger i = 0; i < pageCount; ++i) {
// [self.mutableArray_pageContentViews addObject:[NSNull null]];
// }
}
Please follow below link. this will solve your problem. Also please don't write too much code, it will be easily done with storyboard.
https://github.com/mluton/EmbeddedSwapping

Load images on a image view using horizontal scrolling

I'm loading images on the UIImageView through a string and i want horizontal scrolling to view the images on a UIImageView.
In my xib file I have a scroll view over which there is a image view. I'm using this code but my page is not scrolling and only the first image in the string is loaded.Can anyone please help.
Code:
-(void)viewDidLoad
{
count=1;
// imagesName = [[NSMutableArray alloc]initWithObjects :#"election_band_base.jpg", #"ElectionBoxAPPA-Hindi(1).jpg", #"photos.png", #"business.png", #"health.png", nil];
imagesName1 = [NSString stringWithFormat :#"election_band_base.jpg", #"ElectionBoxAPPA-Hindi(1).jpg", #"photos.png", #"business.png", #"health.png", nil];
[imagesName addObject:imagesName1];
items = [[NSMutableArray alloc]init];
// [_imageView1.image setImage=imagesName1];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// _imageView1.image=[UIImage animatedImageWithImages:imagesName duration:0];
_imageView1.image=[UIImage imageNamed:imagesName1 ];
[self loadScrollView];
}
-(void)loadScrollView
{
scrollView.contentSize = CGSizeMake(0, scrollView.frame.size.height);
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < [imagesName count]; i++) {
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
count=1;
// a page is the width of the scroll view
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * [imagesName count], scrollView.frame.size.height);
//scrollView.contentSize = CGSizeMake(900,80);
scrollView.showsHorizontalScrollIndicator =YES;
scrollView.showsVerticalScrollIndicator = YES;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;
pageControl.numberOfPages = [imagesName count];
pageControl.currentPage = 0;
// pages are created on demand
// load the visible page
// load the page on either side to avoid flashes when the user starts scrolling
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}
- (void)loadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= [imagesName count])
return;
// replace the placeholder if necessary
controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
NSString *deviceType = [UIDevice currentDevice].model;
if([deviceType isEqualToString:#"iPhone"])
{
controller = [[MyViewController alloc] initWithNibName:#"MyViewController" bundle:nil];
}
else{
controller = [[MyViewController alloc] initWithNibName:#"MyViewController_ipad" bundle:nil];
}
[controller initWithPageNumber:page];
[controller setArrData:imagesName];
[viewControllers replaceObjectAtIndex:page withObject:controller];
}
// add the controller's view to the scroll view
if (nil == controller.view.superview) {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
[scrollView addSubview:controller.view];
}
}
- (void)unloadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= [imagesName count]) return;
controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller != [NSNull null]) {
if (nil != controller.view.superview)
[controller.view removeFromSuperview];
[viewControllers replaceObjectAtIndex:page withObject:[NSNull null]];
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// We don't want a "feedback loop" between the UIPageControl and the scroll delegate in
// which a scroll event generated from the user hitting the page control triggers updates from
// the delegate method. We use a boolean to disable the delegate logic when the page control is used.
if (pageControlUsed) {
// do nothing - the scroll was initiated from the page control, not the user dragging
return;
}
// Switch the indicator when more than 50% of the previous/next page is visible
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
// NSLog(#"current page %d",page);
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self unloadScrollViewWithPage:page - 2];
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
[self unloadScrollViewWithPage:page + 2];
count=page+1;
// A possible optimization would be to unload the views+controllers which are no longer visible
}
// At the begin of scroll dragging, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollViewLoc
{
CGFloat pageWidth = scrollViewLoc.frame.size.width;
CGPoint translation = [scrollViewLoc.panGestureRecognizer translationInView:scrollViewLoc.superview];
int page = floor((scrollViewLoc.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
}
// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlUsed = NO;
}
- (IBAction)changePage:(id)sender
{
int page = pageControl.currentPage;
// load the visible page and the page on either side of it (to avoid flashes when the user starts scrolling)
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
// update the scroll view to the appropriate page
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[scrollView scrollRectToVisible:frame animated:YES];
// Set the boolean used when scrolls originate from the UIPageControl. See scrollViewDidScroll: above.
pageControlUsed = YES;
}
So, you want to built the gallery view:
For this implement the following steps:
Add the UIScrollView to the view of your view controller.
In viewDidLoad method: Load the name of the images in the "ImageArray". (I assume all your images have names as "img1.png", "img2.png", "img3.png", ....)
ImageArray=[[NSMutableArray alloc]init];
for (int i=0; i<19; i++) {
NSString *imgtext=[[NSString alloc]initWithFormat:#"img%d",i+1];
[ImageArray addObject:imgtext];
}
In the viewWillAppear method, add the following code:
for (int i = 0; i < ImageArray.count; i++) {
CGRect frame;
frame.origin.x = self.scrollview.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollview.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
UIImage *image = [UIImage imageNamed: [NSString stringWithFormat:#"%#.png",[ImageArray objectAtIndex:i]]];
UIImageView *imageView = [[UIImageView alloc] initWithImage: image];
[imageView setFrame:CGRectMake(0, 0, frame.size.width,frame.size.height )];
[subview addSubview:imageView];
[self.scrollview addSubview:subview];
}
self.scrollview.contentSize = CGSizeMake(self.scrollview.frame.size.width * ImageArray.count, self.scrollview.frame.size.height);
self.scrollview.contentOffset=CGPointMake (self.scrollview.frame.size.width, 0);
Hope it helps.
I have made a scroll view in my app in which I have added multiple images with horizontal scrolling. Below is the function which may help you..
- (void)makeFriendsScrollView{
int friendsCount = 10;
float xPos = 10;
for (int i = 0; i < friendsCount; i++) {
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(xPos,25 , 54, 54)];
imgView.image = [UIImage imageNamed:#"user_default.png"];
[imgView.layer setCornerRadius:27.0];
imgView.clipsToBounds = YES;
[scrollViewFriends addSubview:imgView];
xPos = xPos + 64;
}
scrollViewFriends.contentSize = CGSizeMake(friendsCount*65, 90);
[scrollViewFriends.layer setBorderColor:[UIColor lightGrayColor].CGColor];
[scrollViewFriends.layer setBorderWidth:0.5f];
}
i simply did this in view controller check it out...and change according to your requirement..try this in viewWillAppear method
self.arraname=[NSArray arrayWithObjects:#"1.jpg",#"2.jpg",#"3.jpg", nil];
// int friendsCount = 10;
float xPos = 160;
float x1=0;
float y=60;
for (int i = 0; i < [self.arraname count]; i++)
{
x1=xPos+(260*i);
_imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x1, y, 54, 54)];
_imgView.image = [UIImage imageNamed:[self.arraname objectAtIndex:i]];
[_imgView.layer setCornerRadius:27.0];
_imgView.clipsToBounds = YES;
[self.scroll addSubview:_imgView];
}
NSLog(#"%f",x1);
self.scroll.contentSize=CGSizeMake(x1+200, 0);
self.scroll.showsHorizontalScrollIndicator = YES;
self.scroll.showsVerticalScrollIndicator=NO;
self.scroll.pagingEnabled = YES;

Loading images into a UIScrollView

I'm hoping somebody can help me out here, I'm not sure what else to do. I have a UIScrollView that loads a set of 44 images, and then allows the user to page through them. My code was working, then suddenly it stopped. I have no idea what I have changed so any help would be much appreciated:
The previous view is a UITableView, it passes a string along with the name of the cell that was selected. Here is the ViewDidLoad Method from the ScrollView:
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:#"Answer"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(answerPressed:)];
self.navigationItem.rightBarButtonItem = rightButton;
if([questionSetName isEqualToString:#"Limitations"]){
[self limitationsView];
}
}
Here is the limitationsView:
-(void)limitationsView{
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, -44, self.view.frame.size.width, self.view.frame.size.height)];
scroll.pagingEnabled = YES;
NSArray *unsortedArray = [[NSBundle mainBundle] pathsForResourcesOfType:#"png" inDirectory:#"Images/Limitations"];
NSMutableArray *limitationImages = [[NSMutableArray alloc] init];
for (int x = 0; x<[unsortedArray count]; x++) {
NSString *fileName = [[unsortedArray objectAtIndex:x] lastPathComponent];
[limitationImages insertObject:fileName atIndex:x];
}
NSArray *sortedArray = [limitationImages sortedArrayUsingFunction:finderSortWithLocal
context:(__bridge void *)([NSLocale currentLocale])];
for(int i = 0; i< [sortedArray count]; i++){
CGFloat xOrigin = i * self.view.bounds.size.width;
UIImageView *limitationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];;
[limitationImageView setImage:[UIImage imageNamed:[sortedArray objectAtIndex:i]]];
limitationImageView.contentMode = UIViewContentModeScaleAspectFit;
[scroll addSubview:limitationImageView];
}
scroll.contentSize = CGSizeMake(self.view.frame.size.width * [sortedArray count], self.view.frame.size.height);
[self.view addSubview:scroll];
}
When I get to the end of the LimitationsView method the sortedArray contains all 44 images, and the proper names, if I try and set the background color of the scrollview I can successfully do that. but my images are not loading and I am at a loss as to why?
I would suggest using
NSLog(#"image:%#",[UIImage imageNamed:[limitationsArray objectAtIndex:i]]);
to see if the image is null at that point. If that's the case, then there is a problem with the strings you are storing in that array i.e., they are not identical to the actual names of your images

Resources