Hi my requirement is showing image in scrollview along with that it should display next and previous button.User can scroll the image as well as use buttons to move images.
I have doubt about how to get the index/tag/imagename or anything else when user scroll based on that values buttons should be updated.
Here is my Code
[self arrayInitiaisation];
scrollview.pagingEnabled = YES;
scrollview.alwaysBounceVertical = NO;
scrollview.alwaysBounceHorizontal = YES;
NSInteger numberOfViews = 4;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i*320;
imageView.image = [UIImage imageNamed:[NSString stringWithFormat:#"image%d",i+1]];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.scrollview addSubview:imageView];
imageView.tag = i;
...
Array Initialisation method
-(void) arrayInitialisation {
count=0;
[super viewDidLoad];
images=[NSMutableArray arrayWithObjects : [UIImage imageNamed:#"image1.png"],
[UIImage imageNamed :#"image2.png"],
[UIImage imageNamed :#"image3.png"],
[UIImage imageNamed :#"image4.png"],nil];
[imageView setImage:[images objectAtIndex:0]];
NSLog(#"Array Length :%d",images.count);
[previous setEnabled:NO];
}
Action Methods
- (IBAction)nextButton:(id)sender {}
- (IBAction)prevButton:(id)sender {}
scroll is working correctly but when user clicks on prev and next image is not updating on 'imageview'
Here is my updated code
int count=0;
- (void)viewDidLoad
{
[super viewDidLoad];
[self arrayInitialisation];
[scrollview setScrollEnabled:YES];
self.scrollview =[[UIScrollView alloc] initWithFrame:CGRectMake(30 , 30, 320, 412)];
self.scrollview.delegate=self;
scrollview.pagingEnabled = YES;
scrollview.alwaysBounceVertical=NO;
scrollview.alwaysBounceHorizontal=YES;
scrollview.showsHorizontalScrollIndicator=NO;
NSInteger numberOfViews = 4;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i*320;
imageView = [[UIImageView alloc]initWithFrame:CGRectMake(xOrigin, 0, 320, 412)];
imageView.image = [images objectAtIndex:i];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.scrollview addSubview:imageView];
imageView.tag=i;
}
scrollview.contentSize = CGSizeMake(320*numberOfViews, 412);
scrollview.contentOffset = CGPointMake(0,0);
[self.view addSubview:self.scrollview];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void) arrayInitialisation{
count=0;
[super viewDidLoad];
images=[NSArray arrayWithObjects : [UIImage imageNamed:#"image1.png"],
[UIImage imageNamed :#"image2.png"],
[UIImage imageNamed :#"image3.png"],
[UIImage imageNamed :#"image4.png"],nil];
[imageView setImage:[images objectAtIndex:0]];
NSLog(#"Array Length :%d",images.count);
[previous setEnabled:NO];
}
- (IBAction)nextButton:(id)sender {
if(count==0){
count++;
NSLog(#"Next Button : if Loop %d",count);
[imageView setImage:[images objectAtIndex:count]];
[previous setEnabled:YES];
}
else{
[previous setEnabled:YES];
count++;
NSLog(#"Next Button : else Loop %d",count);
if(count <images.count){
[imageView setImage:[images objectAtIndex:count]];
}
else{
[next setEnabled:NO];
}
}
}
- (IBAction)prevButton:(id)sender {
if(count==0){
//count--;
NSLog(#"prev Button : if Loop %d",count);
[imageView setImage:[images objectAtIndex:count]];
[previous setEnabled:NO];
[next setEnabled:YES];
}
else{
count--;
NSLog(#"prev Button : else Loop %d",count);
[imageView setImage:[images objectAtIndex:count]];
[previous setEnabled:YES];
//[next setEnabled:YES];
}
}
#pragma mark - ScrollView Delegate
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate: (BOOL)decelerate{
//NSLog(#"scrollViewDidEndDragging");
/* count=count+1;
NSLog(#"scrollViewDidEndDragging : %d",count);*/
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//NSLog(#"scrollViewDidScroll");
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset NS_AVAILABLE_IOS(5_0){
//NSLog(#"scrollViewWillEndDragging");
count=count+1;
NSLog(#"scrollViewWillEndDragging : %d",count);
}
I have left and right button for scroll images, and imageview width is same.
I am writing code for scroll image at pressing button.
int pos=0;// ViewDiaLoad
- (IBAction)OnClickLeftButton:(UIButton*)sender
{
if(pos>0)
{
pos -=1;
[scrlDemandMenu scrollRectToVisible:CGRectMake(pos*scrlDemandMenu.frame.size.width, 0, scrlDemandMenu.frame.size.width, scrlDemandMenu.frame.size.height) animated:YES];
}
}
- (IBAction)OnClickRightButton:(UIButton*)sender
{
if(pos<numberOfImages)
{
pos +=1;
[scrlDemandMenu scrollRectToVisible:CGRectMake(pos*scrlDemandMenu.frame.size.width, 0, scrlDemandMenu.frame.size.width, scrlDemandMenu.frame.size.height) animated:YES];
}
}
Set scrollView Deleagte
Scroll View delegate Method
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
pos=scrollView.contentOffset.x/scrollView.frame.size.width;
}
You can use UIPageControl and set and get image according to page index. For more information check out this link
Try below piece of code. I hope it will help. Put this in your .h file
IBOutlet UIScrollView *scrollView;
IBOutlet UIPageControl *pageControl;
NSMutableArray *arrImages;
NSInteger page;
Now in your - (void)viewDidLoad put following lines.
int x = 30;
for (int i=0; i< arrImages.count; i++)
{
UIImageView *imgShow = [[UIImageView alloc]initWithFrame:CGRectMake(x+20, 50, self.view.frame.size.width-100, self.view.frame.size.height-180)];
imgShow.backgroundColor = [UIColor whiteColor];
imgShow.image = [UIImage imageNamed:[arrImages objectAtIndex:i]];
imgShow.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview:imgShow];
x = x+scrollView.frame.size.width;
}
scrollView.contentSize = CGSizeMake(5*self.view.frame.size.width, 0);
pageControl.backgroundColor = [UIColor clearColor];
pageControl.pageIndicatorTintColor = [UIColor grayColor];
pageControl.currentPageIndicatorTintColor = [UIColor blueColor];
[pageControl setTintAdjustmentMode:UIViewTintAdjustmentModeDimmed];
pageControl.numberOfPages = arrTitle.count;
pageControl.currentPage = 0;
implement scroll view delegate.
#pragma mark - ScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView1
{
CGFloat pageWidth = scrollView.frame.size.width;
float fractionalPage = scrollView.contentOffset.x / pageWidth;
page = lround(fractionalPage);
pageControl.currentPage = page;
}
- (IBAction)prevButton:(UIButton *)sender
{
page = page-1;
UIButton *btn = (UIButton *)[sender viewWithTag:sender.tag];
// write your code
for (id obj in btn.subviews)
{
if ([obj isKindOfClass:[UIImageView class]])
{
// write your code
}
else
{
// write your code
}
}
}
- (IBAction)nextButton:(UIButton *)sender
{
page = page+1;
UIButton *btn = (UIButton *)[sender viewWithTag:sender.tag];
// write your code
for (id obj in btn.subviews)
{
if ([obj isKindOfClass:[UIImageView class]])
{
// write your code
}
else
{
// write your code
}
}
}
Related
if(self){
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)];
}
[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:#selector(scrollPages)
userInfo:nil
repeats:NO];
- (void)scrollPages
{
//I want a method here, the timer works for the first image later it will not scroll, so tel me how to introduce delay between images.
}
Add timer call in viewWillAppear:
_slideShowTimer = [NSTimer scheduledTimerWithTimeInterval:K_DEFINE_YOUR_TIME
target:self
selector:#selector(scrollPages)
userInfo:Nil
repeats:YES];
-(void)scrollPages {
if (currentPage>=self.pageControl.numberOfPages) {
currentPage=0;
[self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}
[self scrollToPage:currentPage];
currentPage++;
}
-(void)scrollToPage:(NSInteger)aPage {
float myPageWidth = [self.scrollView frame].size.width;
[self.scrollView setContentOffset:CGPointMake(aPage*myPageWidth,0) animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// Update the page when more than 50% of the previous/next page is visible
if (!pageControlBeingUsed) {
CGFloat pageWidth = self.scrollView.frame.size.width;
pageNumber = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = pageNumber;
}
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
pageNumber1 = pageNumber;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
pageNumber2 = pageNumber;
if(pageNumber == 4 && pageNumber2 == pageNumber1){
//Do any action you want to do from last page or you add by your condition.
}
}
-(void)scrollPages
{
int currentPage = (int)self.scrollView.contentOffset.x / self.scrollView.bounds.size.width;
int totalPages = (int)self.scrollView.contentSize.width / self.scrollView.bounds.size.width;
if(currentPage < totalPages)
{
currentPage++;
}
else
{
currentPage = 1;
}
[self.scrollView setContentOffset:CGPointMake((currentPage-1)*self.scrollView.bounds.size.width,0)];
}
Also enable paging.
So, I have repeating views containing thumbnails, once a thumbnail is pressed the thumbnail ID is sent as the tag.
With this information I want to get the frame of the subview of that view;
- (IBAction)thumbPressed:(id)sender {
NSLog(#"Thumb %i pressed", (int)[sender tag]);
for (int i = 0; i < _thumbCounter; i++) {
if (i == [sender tag]) {
NSLog(#"thumb view %i", i);
//Up To HERE
break;
}
}
// [self moveToVideoControllerWithInfoID:[NSString stringWithFormat:#"%li", (long)[sender tag]]];
}
For the thumbnails to be drawn they're drawn in a random order retrieved by JSON.
The Button
UIButton *thumbButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[thumbButton addTarget:self
action:#selector(thumbPressed:)
forControlEvents:UIControlEventTouchUpInside];
thumbButton.frame = CGRectMake(0, 0, _thumbView.frame.size.width, _thumbView.frame.size.height);
thumbButton.tag = _thumbCounter;
[_thumbView addSubview:thumbButton];
The subview I want to get the frame of
NSString *string = [NSString stringWithFormat:#"***.jpg",Link];
NSURL * imageURL = [NSURL URLWithString:string];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image = [UIImage imageWithData:imageData];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(thumbGap, thumbGap, thumbHeight - 5, thumbHeight - 5)];
imageView.image = image;
[_thumbView addSubview:imageView];
Where the thumbnail shell is drawn
_thumbView = [[ThumbView alloc] initWithFrame:CGRectMake(0, margin, _scrollView.frame.size.width, thumbHeight)];
_thumbView.backgroundColor = [UIColor whiteColor];
_thumbView.thumbId = _thumbCounter;
[_scrollView addSubview:_thumbView];
_thumbview is a class of UIVIEW with the added thumbId
How once that button is pressed can I locate the imageView frame inside of _thumbview ( bare in mind there are multiple ).
First off, let's make life easier for you:
- (IBAction)thumbPressed:(UIButton*)sender {
NSLog(#"Thumb %i pressed", (int)[sender tag]);
ThumbView *thumbView = (ThumbView*)[sender superView];
for(UIView* subview in thumbView.subViews) {
if([subView iKindOfClass:[UIImageView class]]) {
//you got it here
}
}
}
You could shortcut the whole thing by making ThumbView have an imageView property as well.
I've tried to determine that this is what you are doing:
_scrollView
->_thumbView[0]
--->thumbButton
--->imageView
->_thumbView[1]
--->thumbButton
--->imageView
...
->_thumbView[N]
--->thumbButton
--->imageView
Assumed that you want the image view who is in the same thumbView as the button who is pressed.
Best Possible Solution (IMHO):
#Interface ThumbView()
#property (nonatomic,weak) UIImageView *imageView;
#end
AND:
(After making sure to first add, and THEN SET .imageView)
- (IBAction)thumbPressed:(UIButton*)sender {
NSLog(#"Thumb %i pressed", (int)[sender tag]);
UIImageView *imageView = ((ThumbView*)[sender superView]).imageView
}
for (UIView *i in _scrollView.subviews) {
if ([i isKindOfClass:[ThumbView class]]) {
ThumbView *tempThumb = (ThumbView *)i;
if (tempThumb.thumbId == (int)[sender tag]) {
for (UIView *y in tempThumb.subviews) {
if ([y isKindOfClass:[UIImageView class]]) {
UIImageView *tempIMG = (UIImageView *)y;
[self playVideo:[loadedInput objectForKey:#"link"] frame:tempIMG.frame andView:tempThumb];
}
}
}
}
}
In my application having gallery functionality.For Scrolling image i used REPagedScrollView and i want to image zoom on pinch using 2 finger and also want zoom on double tap but i unable to to zoom image on double tap
please resolved my problem.
I tried by below code :
.h file
#interface ViewPhotoVC : UIViewController<UIScrollViewDelegate,UIGestureRecognizerDelegate>
{
REPagedScrollView *scrollView;
UIScrollView *image_scroll;
int current_page;
BOOL is_FullScreen;
}
#property (strong,nonatomic) IBOutlet UIView *slider_view;
.m file
-(void)video_image_Gallery
{
scrollView = [[REPagedScrollView alloc] initWithFrame:self.slider_view.bounds];
scrollView.delegate=self;
// scrollView.pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
// scrollView.pageControl.currentPageIndicatorTintColor = [UIColor grayColor];
current_page=0;
for(int i=0;i<[self.PhotoImgArr count];i++){
self.image_view = [[AsyncImageView alloc] initWithFrame:CGRectMake(0,0, self.slider_view.frame.size.width, self.slider_view.frame.size.height)];
// scrollView.frame=CGRectMake(0, 0, screenwidth, screenheight);
image_scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0,0,screenwidth,screenheight)];
self.image_view.backgroundColor=[UIColor clearColor];
self.image_view.contentMode = UIViewContentModeScaleAspectFit;
self.image_view.clipsToBounds = true;
self.image_view.userInteractionEnabled = YES;
self.image_view.autoresizingMask = ( UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin);
self.image_view.image = [UIImage imageNamed:#"no_image1.png"];
self.image_view.imageURL =[NSURL URLWithString:[self.PhotoImgArr objectAtIndex:i]];
self.image_view.backgroundColor = [UIColor colorWithRed:247.0/255.0 green:246.0/255.0 blue:241.0/255.0 alpha:1];
[image_scroll setDelegate:self];
[image_scroll setShowsHorizontalScrollIndicator:NO];
[image_scroll setShowsVerticalScrollIndicator:NO];
[image_scroll setMaximumZoomScale:8.0];
image_scroll.tag=i+1;
self.PlayVideoBtn.tag=i+1;
self.image_view.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
image_scroll.contentSize = CGSizeMake(self.image_view.bounds.size.width-500, self.image_view.bounds.size.height-300);
image_scroll.decelerationRate = UIScrollViewDecelerationRateFast;
// [image_scroll setMinimumZoomScale:[image_scroll frame].size.width / [self.image_view frame].size.width];
[image_scroll setZoomScale:[image_scroll minimumZoomScale]];
[image_scroll addSubview:self.image_view];
[image_scroll addSubview:self.PlayVideoBtn];
[image_scroll addSubview:self.videoImg];
scrollView.tag=0;
// self.PlayVideoBtn.tag=0;
[scrollView addPage:image_scroll];
}
[self.slider_view addSubview:scrollView];
self.index_lbl.text = [NSString stringWithFormat:#"%d of %lu",(int)self.selected_index+1,(unsigned long)[self.PhotoImgArr count]];
[scrollView scrollToPageWithIndex:self.selected_index animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView1
{
if(scrollView1.tag ==0){
CGFloat pageWidth = scrollView1.frame.size.width;
current_page = floor((scrollView1.contentOffset.x - pageWidth / 2.0) / pageWidth) + 1;
self.index_lbl.text = [NSString stringWithFormat:#"%d of %lu",current_page+1,(unsigned long)[self.PhotoImgArr count]];
if(current_page+1==self.PhotoImgArr.count)
{
self.nextBtn.userInteractionEnabled=NO;
self.nextImg.image=[UIImage imageNamed:#"disable_next.png"];
}
else if(current_page==0)
{
self.prevBtn.userInteractionEnabled=NO;
self.prevImg.image=[UIImage imageNamed:#"disable_prev.png"];
}
else
{
self.nextBtn.userInteractionEnabled=YES;
self.prevBtn.userInteractionEnabled=YES;
self.nextImg.image=[UIImage imageNamed:#"next.png"];
self.prevImg.image=[UIImage imageNamed:#"prev.png"];
}
}
}
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView1 {
if([self.PhotoOrVideo isEqualToString:#"Photo"])
{
if([[scrollView1 viewWithTag:scrollView1.tag].subviews count]>0){
return [[scrollView1 viewWithTag:scrollView1.tag].subviews objectAtIndex:0];
}
}
return nil;
}
Please try the below code:
-(void)setScrollView:(UIScrollView *)scrollView
{
_scrollView=scrollView;
_scrollView.minimumZoomScale=0.2;
_scrollView.maximumZoomScale=3.0;
_scrollView.delegate=self;
}
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
return self.imageView;
}
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
[self.scrollView flashScrollIndicators];
}
I have added view controllers according to my array count and set the content size of the horizontal scroll view.now i want some text to be displayed on each view.
for this i have taken a for loop but i'm not able to add text views over the views.
this is my code:
-(void)loadScrollView
{
scrollView.contentSize = CGSizeMake(0, scrollView.frame.size.height);
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < [_arrUrlLinks count]; i++) {
[controllers addObject:[NSNull null]];
}
// MyViewController1 *controller;
self.viewControllers = controllers;
// self.viewControllers =_txtView;
count=1;
// a page is the width of the scroll view
scrollView.pagingEnabled = YES;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * [_arrUrlLinks count], scrollView.frame.size.height);
scrollView.showsHorizontalScrollIndicator =YES;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.scrollsToTop = NO;
scrollView.delegate = self;
pageControl.numberOfPages = [_arrUrlLinks count];
pageControl.currentPage = 0;
}
- (void)loadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= [_arrUrlLinks count])
return;
controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
NSString *deviceType = [UIDevice currentDevice].model;
if([deviceType isEqualToString:#"iPhone"])
{
controller = [[MyViewController1 alloc] initWithNibName:#"MyViewController1" bundle:nil];
}
else{
controller = [[MyViewController1 alloc] initWithNibName:#"MyViewController1_ipad" bundle:nil];
}
[controller initWithPageNumber: page];
NSLog(#"loadscrollviewwithpage");
[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;
NSLog(#"111111%#",resultDicArray);
NSLog(#"0000000%#",body);
NSLog(#"header======.>>>>..%#",headerstr);
}
[scrollView addSubview:controller.view];
[self downLoadData:page];
}
- (void)unloadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= [_arrUrlLinks 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]];
NSLog(#"Unloadscrollviewwithpage");
}
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
if (pageControlUsed) {
return;
}
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
pageControl.currentPage = page;
[self unloadScrollViewWithPage:page - 2];
[self loadScrollViewWithPage:page - 1];
[self loadScrollViewWithPage:page];
[self loadScrollViewWithPage:page + 1];
[self unloadScrollViewWithPage:page + 2];
count=page+1;
// [self newCountTitleSet];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self loadScrollView];
[self loadScrollViewWithPage:0];
[self loadScrollViewWithPage:1];
}
i have successfully added my controllers over the scroll view now how to add text view over the controllers.
Try this,
....
if (nil == controller.view.superview) {
.....
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller.view.frame = frame;
//Add textview as subview to controller
UITextView *textView = [[UITextView alloc] init];
textView.text = #"hello";
textView.frame = //set frame here
//set tag to textView if needed
[controller.view addSubView:textView];
[scrollView addSubview:controller.view];
NSLog(#"loadscrollviewwithpage................>>>>>>>>>>>>");
}
....
For example you want to 10 diffrent images or textview you could use this logic:
- (void)viewDidLoad {
[super viewDidLoad];
UIScrollView *scr=[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scr.tag = 1;
scr.autoresizingMask=UIViewAutoresizingNone;
[self.view addSubview:scr];
[self setupScrollView:scr];
UIPageControl *pgCtr = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 264, 480, 36)];
[pgCtr setTag:12];
pgCtr.numberOfPages=10;
pgCtr.autoresizingMask=UIViewAutoresizingNone;
[self.view addSubview:pgCtr];
}
- (void)setupScrollView:(UIScrollView*)scrMain {
// we have 10 images here.
// we will add all images into a scrollView & set the appropriate size.
for (int i=1; i<10; i++) {
// create image
UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:#"sti%02i.jpeg",i]];
// create imageView
UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake((i-1)*scrMain.frame.size.width, 0, scrMain.frame.size.width, scrMain.frame.size.height)];
// set scale to fill
imgV.contentMode=UIViewContentModeScaleToFill;
// set image
[imgV setImage:image];
// apply tag to access in future
imgV.tag=i+1;
// add to scrollView
[scrMain addSubview:imgV];
UITextView*txtview =[[UITextView alloc]initWithFrame:CGRectMake(10,50,200,200)];
[txtview setDelegate:self];
[txtview setReturnKeyType:UIReturnKeyDone];
[txtview setTag:1];
[txtview setText:[yourArray ObjectAtIndex:i]];
[txtview setCornerRadius:5];
[scrMain addSubview:txtview];
}
// set the content size to 10 image width
[scrMain setContentSize:CGSizeMake(scrMain.frame.size.width*10, scrMain.frame.size.height)];
}
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;