I'm a noob to Iphone development (3rd day in Xcode) and I am trying to implement pageControl and scrollview so users can swipe between various pages. I'm using this tutorial and I can't figure out how to load/switch views from nib files as opposed to just changing the background color of a view. Any help is greatly appreciated.
MY CODE
Modification of PageControlExampleViewController.m renamed NewsClass2
// Creates the color list the first time this method is invoked. Returns one color object from the list.
+ (UIColor *)pageControlColorWithIndex:(NSUInteger)index {
if (__pageControlColorList == nil) {
__pageControlColorList = [[NSArray alloc] initWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor magentaColor],
[UIColor blueColor], [UIColor orangeColor], [UIColor brownColor], [UIColor grayColor], nil];
}
// Mod the index by the list length to ensure access remains in bounds.
return [__pageControlColorList objectAtIndex:index % [__pageControlColorList count]];
}
//Changing views instead of colors, not working
+ (UIView *)pageControlViewWithIndex:(NSUInteger)index {
if (__pageControlViewrList == nil) {
__pageControlViewrList = [[NSArray alloc] initWithObjects:[[UIView alloc] initWithNibName:#"PageView" bundle:nil], [[UIView alloc] initWithNibName:#"PageView" bundle:nil], [[UIView alloc] initWithNibName:#"PageView" bundle:nil],
[[UIView alloc] initWithNibName:#"PageView" bundle:nil], [[UIView alloc] initWithNibName:#"PageView" bundle:nil], [[UIView alloc] initWithNibName:#"PageView" bundle:nil], [[UIView alloc] initWithNibName:#"PageView" bundle:nil], nil];
}
// Mod the index by the list length to ensure access remains in bounds.
return [__pageControlViewList objectAtIndex:index % [__pageControlViewList count]];
}
// Set the label and background color when the view has finished loading.
- (void)viewDidLoad {
pageNumberLabel.text = [NSString stringWithFormat:#"Page %d", pageNumber + 1];
self.view.backgroundColor = [NewsClass2 pageControlColorWithIndex:pageNumber];
//Setting View Not Working
self.view = [NewsClass2 pageControlViewWithIndex:pageNumber];
}
welcome to Objective C.
First of all you need to set delegate of scroll view like
//in .h file write
#interface ViewController : UIViewController<UIScrollViewDelegate>
// in viewDidLoad
self.scrollView.delegate = self;
then write in delegate method of UIScrollView write...
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat pageWidth = scrollView.frame.size.width;
int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
}
then make an IBAction of valueChange for pageControl like .....
- (IBAction)changePage:(id)sender
{
int page = self.pageControlHelp.currentPage;
CGRect frame = self.scrollViewHelp.frame;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0;
[self.scrollViewHelp scrollRectToVisible:frame animated:YES];
}
And you have done .......
If you have any confusion for this please feel free to ask......
Related
I have a VC with a scrollview and pagecontrol implemented in it. It has three pages, which are all set up correctly and working fine. What I want to be able to do is have the VC load onto different pages depending on what button a user presses.
In the method the button calls I have
ViewController *vc = [[ViewController alloc] init];
vc.pageControl.currentPage = 2;
[self.navigationController pushViewController:vc animated:YES];
When the VC loads, it is loaded onto the correct page (as evidenced by the bubbles at the bottom of the page) but it is displaying the information from page[0]. If I start scrolling, it jumps back to page[0] no matter what I do.
My best guess is that I need to make the VC load to a specific x origin depending on what page I want to display, but I haven't been able to find anything related to this, so I'm quite lost.
Appreciate any help.
EDIT: Here is the code from the VC class. I didn't write this and it is my first time working with PageControl, so I'm trying to learn as I go.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.scrollView = [[UIScrollView alloc] init];
self.scrollView.pagingEnabled = TRUE;
self.scrollView.showsVerticalScrollIndicator = NO;
self.scrollView.showsHorizontalScrollIndicator = NO;
self.scrollView.delegate = self;
firstPage = [[UIView alloc] init];
firstPage.tag = 0;
secondPage = [[UIView alloc] init];
secondPage.tag = 1;
thirdPage = [[UIView alloc] init];
thirdPage.tag = 2;
pages = [[NSArray alloc] initWithObjects:firstPage, secondPage, thirdPage, nil];
// Page Control
self.pageControl = [[UIPageControl alloc] init];
self.pageControl.numberOfPages = 3;
self.pageControl.currentPage = 0;
[self.view addSubview:self.scrollView];
[self.view addSubview:self.pageControl];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// First Page Setup
//
[self setupFirstPage];
// Second Page Setup
//
[self setupSecondPage];
// Third Page Setup
//
[self setupThirdPage];
// Frame everything
//
CGRect screenFrame = [[UIScreen mainScreen] applicationFrame];
CGRect navBarFrame = self.navigationController.navigationBar.frame;
self.scrollView.frame = CGRectMake(0, navBarFrame.size.height, 320, screenFrame.size.height - navBarFrame.size.height);
self.pageControl.frame = CGRectMake(0, screenFrame.size.height - 70, 320, 20);
firstPage.frame = CGRectMake(0, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
secondPage.frame = CGRectMake(320 * secondPage.tag, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
thirdPage.frame = CGRectMake(320 * thirdPage.tag, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
// Add Subviews
//
[self.scrollView addSubview:firstPage];
[self.scrollView addSubview:secondPage];
[self.scrollView addSubview:thirdPage];
self.scrollView.contentSize = CGSizeMake(320 * pages.count, self.scrollView.frame.size.height);
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
}
Try adding this function and calling it right after you set the page number:
- (void)pageSelectorChanged
{
CGRect frame = self.scrollView.frame;
frame.origin.x = frame.size.width * self.pageControl.currentPage;
frame.origin.y = 0;
[self.scrollView scrollRectToVisible:frame animated:NO];
}
I have a scrollview of images, I will like to tab them and will pushed to another view.
once i tab on the image, the whole view should push to another view.
From this View to another view
Detail view
Sorry for not asking the question clearly.
my scrollview
-(void)pictureScrolling
{
//init scrollview in location on screen
scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, 320, 290)];
scrollview.backgroundColor = [UIColor redColor];
//pass image filenames
NSMutableArray *fileNames = nearbyFrog.imageFiles; //[[[NSMutableArray alloc] init] autorelease];
//setup the array of uiimageviews
NSMutableArray *imgArray = [[NSMutableArray alloc] init];
UIImageView *imageView;
//loop through the array imgNames to add file names to imgArray
for (NSString *imageName in fileNames) {
imageView = [[UIImageView alloc] init];
imageView.image = [UIImage imageNamed:imageName];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[imgArray addObject:imageView];
[imageView release];
}
CGSize pageSize = scrollview.frame.size;
NSUInteger page = 0;
for (UIView *viewForScrollView in imgArray) {
[scrollview addSubview:viewForScrollView];
viewForScrollView.frame = CGRectMake(pageSize.width * page++ +10, 0, pageSize.width -20 , pageSize.height);
// making use of the scrollView's frame size (pageSize) so we need to;
// +10 to left offset of image pos (1/2 the gap)
// -20 for UIImageView's width (to leave 10 gap at left and right)
}
//add scroll view to view
[self.view addSubview:scrollview];
scrollview.contentSize = CGSizeMake(pageSize.width * [imgArray count], pageSize.height);
//scrollview.contentSize = CGSizeMake(320 *viewcount + 20, 290 );
scrollview.showsHorizontalScrollIndicator =NO;
[scrollview setPagingEnabled:YES];
scrollview.delegate =self;
//paging function for scrollview
CGRect frame = [[UIScreen mainScreen] applicationFrame];
self.pageControl = [[[UIPageControl alloc] initWithFrame:CGRectMake(0, 100, 100, 50)] autorelease];
self.pageControl.center = CGPointMake(frame.size.width/2, frame.size.height-60);
self.pageControl.numberOfPages = [fileNames count];
[self.view addSubview:self.pageControl];
//handle Touch Even
[pageControl addTarget:self action:#selector(changePage:) forControlEvents:UIControlEventValueChanged];
[imgArray release];
}
anybody knows how to do it or can show me a tutorial?
Thanks
I think this is the best way to implement it
Create your own Custom UIImageView class. This is required to store an additional property which will help you identify which image for clicked.
Create a delegate for that class which is called with the single tap event is raised in the UIImageView
Add the Images inside the scrollview using this custom class. The delegate of this class will tell you which image was tapped. You can use this to push a new view controller passing the image details (if necessary).
You can find some sample code in the ThumbImageView class in the scrollviewSuite sample
http://developer.apple.com/library/ios/#samplecode/ScrollViewSuite/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008904-Intro-DontLinkElementID_2
#implementation MainViewController
#synthesize scrollView,imageView;
- (id) init {
if (self != nil) {
self.title = #"Evolution";
}
return self;}
- (void)viewDidLoad {
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapDetected:)];
tapGesture.numberOfTapsRequired = 1;
tapGesture.numberOfTouchesRequired = 1;
scrollView = [[UIScrollView alloc] initWithFrame:self.view.frame];
int numberOfImages = 32;
CGFloat currentX = 0.0f;
for (int i=1; i <= numberOfImages; i++) {
// create image
NSString *imageName = [NSString stringWithFormat:#"page-%d.jpg", i];
UIImage *image = [UIImage imageNamed:imageName];
imageView = [[UIImageView alloc] initWithImage:image];
// put image on correct position
CGRect rect = imageView.frame;
rect.origin.x = currentX;
imageView.frame = rect;
// update currentX
currentX +=454; //mageView.frame.size.width;
[scrollView addSubview:imageView];
[imageView release];
}
[scrollView addGestureRecognizer:tapGesture];
scrollView.contentSize = CGSizeMake(currentX, 800);
scrollView.pagingEnabled=YES;
scrollView.userInteractionEnabled = YES;
scrollView.maximumZoomScale = 15;
scrollView.minimumZoomScale = 0.5;
scrollView.bounces = NO;
scrollView.bouncesZoom = NO;
scrollView.delegate = self;
scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
[self.view addSubview:scrollView];
[scrollView release];
[super viewDidLoad];}
- (BOOL)shouldAutorotateToInterfaceOrientation(UIInterfaceOrientation)interfaceOrientation{
return YES;}
-(void)tapDetected:(UIGestureRecognizer*)recognizer{
ImageViewController *settings = [[ImageViewController alloc] init];
[self.navigationController pushViewController:settings animated:YES];
[settings release];}
#end
#implementation ImgScrollViewAppDelegate
#synthesize window;#synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application{
LogMethod();
// If you want the status bar to be hidden at launch use this:
// application.statusBarHidden = YES;
//
// To set the status bar as black, use the following:
// application.statusBarStyle = UIStatusBarStyleBlackOpaque;
// Create window
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// this helps in debugging, so that you know "exactly" where your views are placed;
// if you see "red", you are looking at the bare window, otherwise use black
// window.backgroundColor = [UIColor redColor];
viewController = [ [ MainViewController alloc ] init ];
navigationController = [ [ UINavigationController alloc ] initWithRootViewController: viewController ];
/* Anchor the view to the window */
[window addSubview:[navigationController view]];
/* Make the window key and visible */
[window makeKeyAndVisible];
}
#end
in above code i have problem that is when check it on simulator then rotate device left and right. But view not change and i want to change it. how i modify it?
In your view controller implementation there is a method - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation. If you want it to rotate to any orientation, make it return YES. If you only want it to autorotate to some orientations, add an if statement to check and return yes or no.
I've searched and searched for a tutorial for this but none of them are what I'm looking for. I've tried Apple's sample but it is just colors and I don't know how to make it views. All I'm looking for is a screen that will page while showing the page control. Each time the scroll view pages i want it to show a completely different view with buttons, a lot like the home screen of the iPhone. I found the sample code below which works very well with just images, but I'd like to modify to work with separate views. Please Help! Thank you.
- (void)setupPage {
scrollView.delegate = self;
[self.scrollView setBackgroundColor:[UIColor clearColor]];
[scrollView setCanCancelContentTouches:NO];
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView.clipsToBounds = YES;
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
NSUInteger nimages = 0;
CGFloat cx = 0;
for (; ; nimages++) {
NSString *imageName = [NSString stringWithFormat:#"image%d.jpg", (nimages + 1)];
UIImage *image = [UIImage imageNamed:imageName];
if (image == nil) {
break;
}
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.size.height = image.size.height;
rect.size.width = image.size.width;
rect.origin.x = ((scrollView.frame.size.width - image.size.width) / 2) + cx;
rect.origin.y = ((scrollView.frame.size.height - image.size.height) / 2);
imageView.frame = rect;
[scrollView addSubview:imageView];
[imageView release];
cx += scrollView.frame.size.width;
}
self.pageControl.numberOfPages = nimages;
[scrollView setContentSize:CGSizeMake(cx, [scrollView bounds].size.height)];
}
I was experimenting with this just the other day. I'm still getting used to using a UIScrollView but here's how you can add views to your UIScrollView:
UIView *blueView = [[UIView alloc] init];
blueView.frame = CGRectMake(100, 0, 500, 1024);
blueView.backgroundColor = [UIColor colorWithRed:164.0/256 green:176.0/256 blue:224.0/256 alpha:1];
[scrollView addSubview:blueView];
[blueView release];
UIView *orangeView = [[UIView alloc] init];
orangeView.frame = CGRectMake(700, 0, 500, 1024);
orangeView.backgroundColor = [UIColor colorWithRed:252.0/256 green:196.0/256 blue:131.1/256 alpha:1];
[scrollView addSubview:orangeView];
[orangeView release];
Notice that I'm setting the x value in frame.origin of each view so that they're sitting adjacent to each other. You also have to set the content size of the UIScrollView with something like [scrollView setContentSize:CGSizeMake(1200, 1024)]; so that it knows how big its subviews are.
Then, if you need to control a UIPageControl, you would set its numberOfPages to 2 (for the example scrollview above) and change its currentPage property. You could do this by implementing scrollViewDidEndDecelerating:, which is a method in the UIScrollViewDelegate. You could check which "page" the scrollview is at by checking its contentOffset.x value.
Hope this helps!
Here's the Apple PageControl code with images. To use, just drag your images to the project. The default images are image1.jpg, image2.jpg, etc. If you need png, just change the extension to .png.
Then replace the MyViewController.m code with this code, and you've got pagecontrol with Images.
Cheers, Jordan
http://pastebin.com/raw.php?i=c3hS29sC
// Adding UIView to PageControl example
- (id)initWithPageNumber:(int)page {
UIScreen *screen = [UIScreen mainScreen];
CGRect frame = [screen applicationFrame];
frame.origin.y=0;
if (self = [super initWithNibName:#"MyView" bundle:nil]) {
UIView *view = [[UIView alloc] initWithFrame:frame];
[self.view addSubview:view];
// Add whatever you want to the view here.
[view release];
pageNumber = page;
}
return self;
}
Here's another answer...
NSArray* nibViews = [[NSBundle mainBundle] loadNibNamed:#"Views" owner:self options:nil];
infoView = [nibViews objectAtIndex:0];
[self.view addSubview:infoView];
Then you have your view.
Cheers
I try to make following: Horizontal list of images, that I can select and do something with it. For example flip image around x axis. I know how to rotate image. I created scrollview and load it with images. I added event handler when I tap on image. But I don't know how to do something with tapped image. How to code method to do something with tapped image?
- (void)viewDidLoad {
[super viewDidLoad];
img1 = [UIImage imageNamed:#"imgTest.jpg"];
img2 = [UIImage imageNamed:#"imgTest2.jpg"];
arrayOfImages = [[NSMutableArray alloc] init];
[arrayOfImages addObject:img1];
[arrayOfImages addObject:img2];
[arrayOfImages addObject:img1];
[arrayOfImages addObject:img2];
scrollView = [[UIScrollView alloc] init];
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
scrollView.directionalLockEnabled = YES;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.delegate = self;
scrollView.backgroundColor = [UIColor blueColor];
scrollView.autoresizesSubviews = YES;
scrollView.frame = CGRectMake(0, 0, 320, 128);
[self.view addSubview:scrollView];
UIImage *imageToAdd;
int x = 0;
int y = 0;
for(imageToAdd in arrayOfImages)
{
UIImageView *temp = [[UIImageView alloc] initWithImage:imageToAdd];
temp.frame = CGRectMake(x, y, 128, 128);
temp.userInteractionEnabled = YES;
x += 135;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(imageTapped:)];
[temp addGestureRecognizer:tap];
[scrollView addSubview:temp];
}
...
- (void)imageTapped:(UIGestureRecognizer *)sender
{
// how to get reference on selected item in scrollview???
}
A gesture recognizer has a view property that returns the view associated with the recognizer. Since you know that it'll be a UIImageView you can simply cast it and use it as in:
UIImageView *iv = (UIImageView *)[sender view];
And your image can then be queried via:
UIImage *image = [iv image];
If you need to know the index in your array, there are two ways: either simply use [arrayOfImages indexOfObject:image];, or you can assign tags (numbers) to views and use them. A tag is not used by Apple, it's only here so we developers can "mark" views in some way. For example:
NSInteger counter = 0;
for(imageToAdd in arrayOfImages)
{
UIImageView *temp = [[UIImageView alloc] initWithImage:imageToAdd];
count.tag = counter++;
...
}
Then, in your imageTapped:, you can query the index via tag:
NSInteger index = [imageView tag];