UIViewControllers in ContentView of UIScrollView? - ios

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

Related

UIScrollView forcing inside view to goes up after first touch

I have a UIScrollView to pan some photos. After loading the view, when I touch the page (anywhere within) it makes my insideview (UIImageView) to goes up.
Here is the photo when it loads (the green is the inside UIView, the black the UIScrollView).
Fist load view:
After the touch:
Here is the code that generates it:
Adding the view to the scrollview:
- (void)loadPage:(NSInteger)page {
CGRect frame = self.scrollView.bounds;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
// 3
NSURL *eventImageURL = [NSURL URLWithString:[[self.pageImages objectAtIndex:page] imageURL]];
UIImageView *newPageView = [[UIImageView alloc]init];
[newPageView setImageWithURL:eventImageURL placeholderImage:nil usingActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
newPageView.contentMode = UIViewContentModeScaleAspectFit;
newPageView.frame=frame;
newPageView.tag=page;
newPageView.userInteractionEnabled=NO;
newPageView.backgroundColor=[UIColor greenColor];
newPageView.clipsToBounds=YES;
[self.scrollView addSubview:newPageView];
}
The scroll view setup:
- (void)viewDidLoad {
[super viewDidLoad];
CGSize scrollableSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height);
[self.scrollView setContentSize:scrollableSize];
// Do any additional setup after loading the view from its nib.
// 1
NSInteger pageCount = self.pageImages.count;
// 2
self.pageControl.currentPage = 0;
self.pageControl.numberOfPages = pageCount;
// 3
self.pageViews = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < pageCount; ++i) {
[self.pageViews addObject:[NSNull null]];
}
self.scrollView.minimumZoomScale=1.0;
self.scrollView.maximumZoomScale=2.0;
self.scrollView.clipsToBounds=YES;
self.scrollView.contentSize=CGSizeMake(1280, 960);
self.scrollView.tag=10;
[self.scrollView setUserInteractionEnabled:YES];
[self.scrollView setMultipleTouchEnabled:YES];
}
Found it.
On viewdidload I set:
self.automaticallyAdjustsScrollViewInsets = NO;
And everything works fine.

iOS Implicit conversion of 'int' to 'UIColor*' is disallowed with ARC

I have a pickerview that is getting its information from a separate AFPickerView file. I'm getting the error "Implicit conversion of 'int' to 'UIColor*' is disallowed with ARC". Any suggestions on an easy fix for this?
Here is the code that it effects:
[visibleViews minusSet:recycledViews];
// add missing pages
for (int index = firstNeededViewIndex; index <= lastNeededViewIndex; index++)
{
if (![self isDisplayingViewForIndex:index])
{
UILabel *label = (UILabel *)[self dequeueRecycledView];
if (label == nil)
{
label = [[UILabel alloc] initWithFrame:CGRectMake(_rowIndent, 0, self.frame.size.width - _rowIndent, 39.0)];
label.backgroundColor = [UIColor clearColor];
label.font = self.rowFont;
label.textColor = RGBACOLOR(0.0, 0.0, 0.0, 0.75);
}
[self configureView:label atIndex:index];
[contentView addSubview:label];
[visibleViews addObject:label];
}
}
}
Here is the full code:
#import "AFPickerView.h"
#implementation AFPickerView
#pragma mark - Synthesization
#synthesize dataSource;
#synthesize delegate;
#synthesize selectedRow = currentRow;
#synthesize rowFont = _rowFont;
#synthesize rowIndent = _rowIndent;
#pragma mark - Custom getters/setters
- (void)setSelectedRow:(int)selectedRow
{
if (selectedRow >= rowsCount)
return;
currentRow = selectedRow;
[contentView setContentOffset:CGPointMake(0.0, 39.0 * currentRow) animated:NO];
}
- (void)setRowFont:(UIFont *)rowFont
{
_rowFont = rowFont;
for (UILabel *aLabel in visibleViews)
{
aLabel.font = _rowFont;
}
for (UILabel *aLabel in recycledViews)
{
aLabel.font = _rowFont;
}
}
- (void)setRowIndent:(CGFloat)rowIndent
{
_rowIndent = rowIndent;
for (UILabel *aLabel in visibleViews)
{
CGRect frame = aLabel.frame;
frame.origin.x = _rowIndent;
frame.size.width = self.frame.size.width - _rowIndent;
aLabel.frame = frame;
}
for (UILabel *aLabel in recycledViews)
{
CGRect frame = aLabel.frame;
frame.origin.x = _rowIndent;
frame.size.width = self.frame.size.width - _rowIndent;
aLabel.frame = frame;
}
}
#pragma mark - Initialization
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
// setup
[self setup];
// backgound
UIImageView *bacground = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pickerBackground.png"]];
[self addSubview:bacground];
// content
contentView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0, 0.0, frame.size.width, frame.size.height)];
contentView.showsHorizontalScrollIndicator = NO;
contentView.showsVerticalScrollIndicator = NO;
contentView.delegate = self;
[self addSubview:contentView];
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(didTap:)];
[contentView addGestureRecognizer:tapRecognizer];
// shadows
UIImageView *shadows = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"pickerShadows.png"]];
[self addSubview:shadows];
// glass
UIImage *glassImage = [UIImage imageNamed:#"pickerGlass.png"];
glassImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, 76.0, glassImage.size.width, glassImage.size.height)];
glassImageView.image = glassImage;
[self addSubview:glassImageView];
}
return self;
}
- (void)setup
{
_rowFont = [UIFont boldSystemFontOfSize:24.0];
_rowIndent = 30.0;
currentRow = 0;
rowsCount = 0;
visibleViews = [[NSMutableSet alloc] init];
recycledViews = [[NSMutableSet alloc] init];
}
#pragma mark - Buisness
- (void)reloadData
{
// empry views
currentRow = 0;
rowsCount = 0;
for (UIView *aView in visibleViews)
[aView removeFromSuperview];
for (UIView *aView in recycledViews)
[aView removeFromSuperview];
visibleViews = [[NSMutableSet alloc] init];
recycledViews = [[NSMutableSet alloc] init];
rowsCount = [dataSource numberOfRowsInPickerView:self];
[contentView setContentOffset:CGPointMake(0.0, 0.0) animated:NO];
contentView.contentSize = CGSizeMake(contentView.frame.size.width, 39.0 * rowsCount + 4 * 39.0);
[self tileViews];
}
- (void)determineCurrentRow
{
CGFloat delta = contentView.contentOffset.y;
int position = round(delta / 39.0);
currentRow = position;
[contentView setContentOffset:CGPointMake(0.0, 39.0 * position) animated:YES];
[delegate pickerView:self didSelectRow:currentRow];
}
- (void)didTap:(id)sender
{
UITapGestureRecognizer *tapRecognizer = (UITapGestureRecognizer *)sender;
CGPoint point = [tapRecognizer locationInView:self];
int steps = floor(point.y / 39) - 2;
[self makeSteps:steps];
}
- (void)makeSteps:(int)steps
{
if (steps == 0 || steps > 2 || steps < -2)
return;
[contentView setContentOffset:CGPointMake(0.0, 39.0 * currentRow) animated:NO];
int newRow = currentRow + steps;
if (newRow < 0 || newRow >= rowsCount)
{
if (steps == -2)
[self makeSteps:-1];
else if (steps == 2)
[self makeSteps:1];
return;
}
currentRow = currentRow + steps;
[contentView setContentOffset:CGPointMake(0.0, 39.0 * currentRow) animated:YES];
[delegate pickerView:self didSelectRow:currentRow];
}
#pragma mark - recycle queue
- (UIView *)dequeueRecycledView
{
UIView *aView = [recycledViews anyObject];
if (aView)
[recycledViews removeObject:aView];
return aView;
}
- (BOOL)isDisplayingViewForIndex:(NSUInteger)index
{
BOOL foundPage = NO;
for (UIView *aView in visibleViews)
{
int viewIndex = aView.frame.origin.y / 39.0 - 2;
if (viewIndex == index)
{
foundPage = YES;
break;
}
}
return foundPage;
}
- (void)tileViews
{
// Calculate which pages are visible
CGRect visibleBounds = contentView.bounds;
int firstNeededViewIndex = floorf(CGRectGetMinY(visibleBounds) / 39.0) - 2;
int lastNeededViewIndex = floorf((CGRectGetMaxY(visibleBounds) / 39.0)) - 2;
firstNeededViewIndex = MAX(firstNeededViewIndex, 0);
lastNeededViewIndex = MIN(lastNeededViewIndex, rowsCount - 1);
// Recycle no-longer-visible pages
for (UIView *aView in visibleViews)
{
int viewIndex = aView.frame.origin.y / 39 - 2;
if (viewIndex < firstNeededViewIndex || viewIndex > lastNeededViewIndex)
{
[recycledViews addObject:aView];
[aView removeFromSuperview];
}
}
[visibleViews minusSet:recycledViews];
// add missing pages
for (int index = firstNeededViewIndex; index <= lastNeededViewIndex; index++)
{
if (![self isDisplayingViewForIndex:index])
{
UILabel *label = (UILabel *)[self dequeueRecycledView];
if (label == nil)
{
label = [[UILabel alloc] initWithFrame:CGRectMake(_rowIndent, 0, self.frame.size.width - _rowIndent, 39.0)];
label.backgroundColor = [UIColor clearColor];
label.font = self.rowFont;
label.textColor = RGBACOLOR(0.0, 0.0, 0.0, 0.75);
}
[self configureView:label atIndex:index];
[contentView addSubview:label];
[visibleViews addObject:label];
}
}
}
- (void)configureView:(UIView *)view atIndex:(NSUInteger)index
{
UILabel *label = (UILabel *)view;
label.text = [dataSource pickerView:self titleForRow:index];
CGRect frame = label.frame;
frame.origin.y = 39.0 * index + 78.0;
label.frame = frame;
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[self tileViews];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
if (!decelerate)
[self determineCurrentRow];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self determineCurrentRow];
}
#end
This should work with ARC. Replace RGBACOLOR with colorWithRed:green:blue:alpha
label.textColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.75f];

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

Load images on a image view using horizontal scrolling

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

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

Resources