how to swipe the multiple images in single view in ios - ios

I made multiple image swipping in single view.In that app,there is only one view that has an image on it. I want to be able to swipe left to right and right to left and have the first image go out of the view and the second image to come in.I am trying the code.But it is not worked for me.Please any body guide me.I am new to the image swipping.Thanks in advance.
scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 190)];
scrollView.showsVerticalScrollIndicator=YES;
scrollView.userInteractionEnabled=YES;
scrollView.delegate = self;
scrollView.scrollEnabled = YES;
scrollWidth = 120;
scrollView.contentSize = CGSizeMake(scrollWidth,80);
[self.view addSubview:scrollView];
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *err;
NSString *strResponse=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"response is %#",strResponse);
dict1=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&err];
NSLog(#"vals are %#",dict1);
NSString *strImg;
url=#"myimageurl";
str=[dict1 valueForKey:#"image_names"];
arrImages=[str componentsSeparatedByString:#","];
for(int index=0; index < [arrImages count]; index++)
{
NSLog(#"image: %#",[arrImages objectAtIndex:index]);
if (str!=nil)
{
strImg=[url stringByAppendingString:[arrImages objectAtIndex:index]];
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strImg]];
if(data == nil) return;
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *img=[UIImage imageWithData: data];
imgView.image=img;
});
});
}
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch * touch = [[event allTouches] anyObject];
for(int index=0;index<[arrImages count];index++)
{
UIImageView *imgView = [arrImages objectAtIndex:index];
NSLog(#"x=%f,y=%f,width =%f,height=%f",imgView.frame.origin.x,imgView.frame.origin.y,imgView.frame.size.width,imgView.frame.size.height);
NSLog(#"x= %f,y=%f",[touch locationInView:self.view].x,[touch locationInView:self.view].y) ;
if(CGRectContainsPoint([imgView frame], [touch locationInView:scrollview]))
{
[self ShowDetailView:imgView];
break;
}
}
}

First of all set the pagingEnabled property scrollview.pagingEnabled = YES;.
Then set the correct contentSize for the scrollView.
And last but not least you must set the width of contentSize to be a multiple of scrollView.frame.size.width.
I.E. If you have 3 images and your scrollView has a width of 320 pixel you contentSize must be 320x3 = 960 pixel

You may want to adjust scrollView.contentSize.width by amountOfImages * scrollWidth.
Beside this, you really should create a new object for every image.
It could handle image downloading, validating, and touch handling (even with a single transparent button upont the image). You could completly wipe out that weird touchesBegan code from your controller, and you could forget about coordinates entirely.
Also you could stop progressing downloads that have way scrolled out this way, so performance can grow.

.h file #import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UIScrollViewDelegate,UIScrollViewAccessibilityDelegate>
{
UIScrollView *scrView;
NSMutableArray *arrimage;
UIImageView *imgview;
}
#end
.M file
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
[scrollView setBackgroundColor:[UIColor redColor]];
scrollView.contentSize = CGSizeMake(320, 465);
[scrollView setScrollEnabled:YES];
[scrollView setPagingEnabled:YES];
[scrollView setAlwaysBounceVertical:NO];
[self.view addSubview:scrollView];
arrimage = [[NSMutableArray alloc]initWithObjects:#"1.jpeg",#"2.jpeg",#"3.jpeg",#"4.jpeg",#"5.jpeg",#"6.jpeg",#"7.jpeg",#"8.jpeg",#"9.jpeg",#"10.jpeg", nil];
for (int i = 0; i < [arrimage count]; i++)
{
CGFloat xOrigin = i * scrollView.frame.size.width;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, scrollView.frame.size.width, scrollView.frame.size.height)];
[imageView setImage:[UIImage imageNamed:[arrimage objectAtIndex:i]]];
[imageView setContentMode:UIViewContentModeScaleAspectFit];
[scrollView addSubview:imageView];
}
[scrollView setContentSize:CGSizeMake(scrollView.frame.size.width * [arrimage count], scrollView.frame.size.height)];
}

Related

How to autoscroll images one by one by the interval of 2 seconds, using Objective C?

I have made scrollview for the few collection of images and I want it to autoscroll the images one by one by the interval of 2 sec. By the below code I could able to make all images slide at a time, but I want one image to scroll then other with respect to time.
-(void)scrollPages{
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height)];
scrollView.contentSize = CGSizeMake(320, 465);
[scrollView setScrollEnabled:YES];
[scrollView setPagingEnabled:YES];
[scrollView setAlwaysBounceVertical:NO];
[self.uiSubView addSubview:scrollView];
NSMutableArray *arrImage = [NSMutableArray arrayWithObjects:#"a.jpeg", #"cat.jpg", #"s.jpeg",#"ss.jpeg", nil];
for (int i = 0; i < [arrImage count]; i++)
{
CGFloat xOrigin = i * scrollView.frame.size.width;
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(xOrigin, 0, scrollView.frame.size.width, scrollView.frame.size.height)];
[imageView setImage:[UIImage imageNamed:[arrImage objectAtIndex:i]]];
[imageView setContentMode: UIViewContentModeScaleAspectFit];
[scrollView addSubview:imageView];
}
[scrollView setContentSize:CGSizeMake(scrollView.frame.size.width * [arrImage count], scrollView.frame.size.height)];
CGFloat currentOffset = scrollView.contentOffset.x;
if(currentOffset < 2500){
CGFloat newOffset = currentOffset + 1250;
[UIScrollView beginAnimations:nil context:NULL];
[UIScrollView setAnimationDuration:3];
[scrollView setContentOffset:CGPointMake(newOffset,0.0) animated:YES];
}
Try simple recursion with dispatch_after function.
Something like this:
-(void)scrollToNextImage{
//place here code for computing and setting scrollview offset
_weak typeof(self) weakSelf = self; //for avoiding retain cycle
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[weakSelf scrollToNextImage];
});
}
Please be aware that with this case images will be scrolled even when viewcontroller will disappear. Recursion will end only after closing viewcontroller. If you don't want such behavior you can add extra condition for checking if viewcontroller is visible before dispatching next scroll - you can check how to do his here: How to tell if UIViewController's view is visible

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.

UIScrollView did zoom but subview stay unchanged

I'm currently developping an iPad app and I need a "Slideshow"
So I create a first UIScrollView which will be used as pager and in the viewDidLoad I use a "for" loop to put the content in the UIScrollView.
Here is the loop :
for (int i = 0; i < self.thumbs.count; i++) {
UIScrollView *subScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(self.ThumbsSlider.frame.size.width * i, 0, self.ThumbsSlider.frame.size.width, self.ThumbsSlider.frame.size.height)];
[subScroll setDelegate:self];
[subScroll setScrollEnabled:YES];
[subScroll setBouncesZoom:YES];
[subScroll setClipsToBounds:YES];
[subScroll setContentMode:UIViewContentModeCenter];
subviewImage = [[AsyncImageView alloc] initWithFrame:CGRectMake(0 , 0, subScroll.frame.size.width, subScroll.frame.size.height)];
subviewImage.contentMode = UIViewContentModeScaleAspectFit;
subviewImage.userInteractionEnabled = YES;
subviewImage.image = [UIImage imageNamed:#"no-image.jpg"];
subviewImage.imageURL = [NSURL URLWithString:[self.thumbs objectAtIndex:i]];
[subScroll addSubview:subviewImage];
subScroll.minimumZoomScale = 1.0;
subScroll.maximumZoomScale = 3.0;
[[subScroll delegate]viewForZoomingInScrollView:subScroll];
[self.ThumbsSlider addSubview:subScroll];
}
When I launch the app on my iPad, there is no crashes.
But, when I try to zoom, the contentSize of my subScroll change but the subviewImage doesn't zoom !
Can someone explain me why ?
Thanks in advance !
Put this function in your controller
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
for (UIView *imageView in scrollView.subviews)
{
if ([imageView isKindOfClass:[AsyncImageView Class]])
{
return imageView;
}
}
return nil;
}
And remove below line from loop:
[[subScroll delegate]viewForZoomingInScrollView:subScroll];

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