Load images on a image view using horizontal scrolling - ios

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;

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

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

how to add text view and image view on different views

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)];
}

key value coding complaint error

i am using this code to scroll the pages horizontally but i am getting this error:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0xc76a3b0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key image.'
why is this error coming and how to rectify this.
-(void)loadScrollView
{
_scrollView.contentSize = CGSizeMake(0, _scrollView.frame.size.height);
// [[SharedUtilities getInstance]RemoveActivityIndicatorView];
NSMutableArray *controllers1 = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < [_arrUrlLinks count]; i++) {
[controllers1 addObject:[NSNull null]];
}
self.viewControllers1 = controllers1;
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 = NO;
_scrollView.showsVerticalScrollIndicator = NO;
_scrollView.scrollsToTop = NO;
_scrollView.delegate = self;
pageControl.numberOfPages = [_arrUrlLinks 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 >= [_arrUrlLinks count])
return;
// replace the placeholder if necessary
controller1 = [viewControllers1 objectAtIndex:page];
if ((NSNull *)controller1 == [NSNull null]) {
NSString *deviceType = [UIDevice currentDevice].model;
if([deviceType isEqualToString:#"iPhone"])
{
controller1 = [[MyViewController alloc] initWithNibName:#"MyViewController" bundle:nil];
}
else{
controller1 = [[MyViewController alloc] initWithNibName:#"MyViewController_ipad" bundle:nil];
}
[controller1 initWithPageNumber:page];
[controller1 setArrData:_arrUrlLinks];
[viewControllers1 replaceObjectAtIndex:page withObject:controller1];
//[controller release];
}
// add the controller's view to the scroll view
if (nil == controller1.view.superview) {
CGRect frame = _scrollView.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
controller1.view.frame = frame;
[_scrollView addSubview:controller1.view];
}
}
- (void)unloadScrollViewWithPage:(int)page {
if (page < 0) return;
if (page >= [_arrUrlLinks count]) return;
controller1 = [viewControllers1 objectAtIndex:page];
if ((NSNull *)controller1 != [NSNull null]) {
if (nil != controller1.view.superview)
[controller1.view removeFromSuperview];
[viewControllers1 replaceObjectAtIndex:page withObject:[NSNull null]];
// [[NSURLCache sharedURLCache] removeAllCachedResponses];
}
}
- (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;
// [self newCountTitleSet];
// 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;
if(translation.x > 0)
{
if(count!=0)
{
if(page==0)
{
[self DownLoadDataPrevious:count-1];
}
}
else{
if(page==1)
{
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
btnPreviousNews.userInteractionEnabled=FALSE;
}
}
} else
{
btnPreviousNews.userInteractionEnabled=TRUE;
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow1_prev.png"] forState:UIControlStateNormal];
if(count+1!=[_arrUrlLinks count])
{
if(page+1==[_arrUrlLinks count])
{
[self DownLoadDataNext:count+1];
}
count=count+1;
}
}
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlUsed = NO;
}
- (IBAction)changePageToNext:(id)sender {
btnPreviousNews.userInteractionEnabled=TRUE;
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow1_prev.png"] forState:UIControlStateNormal];
int page = count;
// 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;
count=count+1;
// [self newCountTitleSet];
}
- (IBAction)changePageToPrev:(id)sender {
// CGFloat pageWidth = scrollView.frame.size.width;
// int page2 = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
// NSLog(#"current page %d",page2);
//
count=count-1;
NSLog(#"count %d",count);
int page = count-1;
NSLog(#"page %d",page);
if(count==0)
{
if(page==0)
{
[btnPreviousNews setImage:[UIImage imageNamed:#"arrow2_prev.png"] forState:UIControlStateNormal];
btnPreviousNews.userInteractionEnabled=FALSE;
}
if(page>=0)
{
// [self newCountTitleSet];
}
}
else{
if(page<0)
{
[self DownLoadDataPrevious:count-1];
_lblNewsCount.text=[NSString stringWithFormat:#"%d/%d",1,[_arrUrlLinks count]];
}
else{
// [self newCountTitleSet];
}
}
// 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;
}
i am using :
NSURL *imgurl =[NSURL URLWithString:[[Dic valueForKey:#"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
self._imageView1.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:imgurl]];
to get the images from the dictionary and show them on scroll view
There should be a two reasons.
Dic might not be the NSDictionary
if( [Dic isKindOfClass:[NSDictionary class]] )
{
NSURL *imgurl =[NSURL URLWithString:[[Dic valueForKey:#"image"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
self._imageView1.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:imgurl]];
}
_imageView1 is not UIImageView

Received memory warning. in gallery section Xcode

I am making a handbook table cell in my app and i have 7 pages which each are the images and I'm using uiscrollview with page control but when i run the app it says Received memory warning.
and then the app freezes and automatically shuts down, what should i do and this is my code.
#interface HS_HandbookViewController ()
#property (nonatomic, strong) NSArray *pageImages;
#property (nonatomic, strong) NSMutableArray *pageViews;
- (void)loadVisiblePages;
- (void)loadPage:(NSInteger)page;
- (void)purgePage:(NSInteger)page;
#end
#implementation HS_HandbookViewController
#synthesize scrollView = _scrollView;
#synthesize pageControl = _pageControl;
#synthesize pageImages = _pageImages;
#synthesize pageViews = _pageViews;
#pragma mark -
- (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 we want to load
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.pageImages.count; i++) {
[self purgePage:i];
}
}
- (UIImage *)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
- (void)loadPage:(NSInteger)page {
if (page < 0 || page >= self.pageImages.count) {
// If it's outside the range of what we have to display, then do nothing
return;
}
// Load an individual page, first seeing if we've already loaded it
UIView *pageView = [self.pageViews objectAtIndex:page];
if ((NSNull*)pageView == [NSNull null]) {
CGRect frame = self.scrollView.bounds;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0.0f;
UIImageView *newPageView = [[UIImageView alloc] initWithImage:[self.pageImages objectAtIndex:page]];
newPageView.contentMode = UIViewContentModeScaleAspectFit;
newPageView.frame = frame;
[self.scrollView addSubview:newPageView];
[self.pageViews replaceObjectAtIndex:page withObject:newPageView];
}
}
- (void)purgePage:(NSInteger)page {
if (page < 0 || page >= self.pageImages.count) {
// If it's outside the range of what we have to display, then do nothing
return;
}
// Remove a page from the scroll view and reset the container array
UIView *pageView = [self.pageViews objectAtIndex:page];
if ((NSNull*)pageView != [NSNull null]) {
[pageView removeFromSuperview];
[self.pageViews replaceObjectAtIndex:page withObject:[NSNull null]];
}
}
#pragma mark -
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Student Handbook";
// Set up the image we want to scroll & zoom and add it to the scroll view
self.pageImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"page 1 handbook.png"],
[UIImage imageNamed:#"page 2 handbook.png"],
[UIImage imageNamed:#"page 3 hand book.png"],
[UIImage imageNamed:#"page 4 handbook.png"],
[UIImage imageNamed:#"page 5 handbook.png"],
[UIImage imageNamed:#"page 6 handbook.png"],
[UIImage imageNamed:#"page 7 handbook.png"],
nil];
NSInteger pageCount = self.pageImages.count;
// Set up the page control
self.pageControl.currentPage = 0;
self.pageControl.numberOfPages = pageCount;
// Set up the array to hold the views for each page
self.pageViews = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < pageCount; ++i) {
[self.pageViews addObject:[NSNull null]];
}
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// Set up the content size of the scroll view
CGSize pagesScrollViewSize = self.scrollView.frame.size;
self.scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * self.pageImages.count, pagesScrollViewSize.height);
// Load the initial set of pages that are on screen
[self loadVisiblePages];
}
- (void)viewDidUnload {
[super viewDidUnload];
self.scrollView = nil;
self.pageControl = nil;
self.pageImages = nil;
self.pageViews = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// Load the pages which are now on screen
[self loadVisiblePages];
}
#end
First of all make sure you have not another apps running ( double tap on home button and flick all running apps to close ). May be images are big and there is not enough memory in your device. If you able to run your app after it try to figure out if you have not memory leaks. Swipe few times and follow your memory.
If you use ARC than assign nil to your vars since you are not going to use them.

Resources