UIScrollView with pages enabled and device rotation/orientation changes (MADNESS) - objective-c

I'm having a hard time getting this right.
I've got a UIScrollView, with paging enabled. It is managed by a view controller (MainViewController) and each page is managed by a PageViewController, its view added as a subview of the scrollView at the proper offset. Scrolling is left-right, for standard orientation iPhone app. Works well. Basically exactly like the sample provided by Apple and also like the Weather app provided with the iPhone.
However, when I try to support other orientations, things don't work very well. I've supported every orientation in both MainViewController and PageViewController with this method:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
However, when I rotate the device, my pages become quite skewed, and there are lots of drawing glitches, especially if only some of the pages have been loaded, then I rotate, then scroll more, etc... Very messy.
I've told my views to support auto-resizing with
theView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
But to no avail. It seems to just stretch and distort my views.
In my MainViewController, I added this line in an attempt to resize all my pages' views:
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * ([self.viewControllers count]), self.scrollView.frame.size.height);
for (int i = 0; i < [self.viewControllers count]; i++) {
PageViewController *controller = [self.viewControllers objectAtIndex:i];
if ((NSNull *)controller == [NSNull null])
continue;
NSLog(#"Changing frame: %d", i);
CGRect frame = self.scrollView.frame;
frame.origin.x = frame.size.width * i;
frame.origin.y = 0;
controller.view.frame = frame;
}
}
But it didn't help too much (because I lazily load the views, so not all of them are necessarily loaded when this executes).
Is there any way to solve this problem?

I have successfully achieved this using below method:
.h file code:
#interface ScrollViewController2 : UIViewController <UIWebViewDelegate, UIScrollViewDelegate> {
NSMutableArray *views;
int currentPage;
IBOutlet UIScrollView *scrollView;
BOOL bolPageControlUsed;
int intCurrIndex;
NSMutableArray *arrayContentData;
NSMutableArray *viewControllers;
}
#property (nonatomic, retain) IBOutlet UIScrollView *scrollView;
#property (nonatomic, retain) NSMutableArray *arrayContentData;
#property (nonatomic, retain) NSMutableArray *viewControllers;
#property (nonatomic) BOOL bolPageControlUsed;
#property (nonatomic) int intCurrIndex;
-(void)bindPages;
- (void)setUpScrollView;
- (void)alignSubviews;
- (NSURLRequest *)getPageFromDocumentsDirectory:(NSString *)pstrPageName;
-(void)initiateScrollView;
-(void)loadScrollViewWithPage:(int)page;
============================================================================================
.m file
#synthesize scrollView;
#synthesize arrayContentData, viewControllers, bolPageControlUsed, intCurrIndex;
- (void)viewDidLoad {
[super viewDidLoad];
[self bindPages];
//[self setUpScrollView];
[self initiateScrollView];
}
#pragma mark -
#pragma mark Bind Pages
-(void)bindPages{
self.arrayContentData = [[NSMutableArray alloc] init];
[self.arrayContentData addObject:#"1.html"];
[self.arrayContentData addObject:#"2.html"];
[self.arrayContentData addObject:#"3.html"];
[self.arrayContentData addObject:#"4.html"];
[self.arrayContentData addObject:#"5.html"];
[self.arrayContentData addObject:#"6.html"];
[self.arrayContentData addObject:#"1.html"];
[self.arrayContentData addObject:#"2.html"];
[self.arrayContentData addObject:#"3.html"];
[self.arrayContentData addObject:#"4.html"];
[self.arrayContentData addObject:#"5.html"];
[self.arrayContentData addObject:#"6.html"];
[self.arrayContentData addObject:#"1.html"];
[self.arrayContentData addObject:#"2.html"];
[self.arrayContentData addObject:#"3.html"];
[self.arrayContentData addObject:#"4.html"];
[self.arrayContentData addObject:#"5.html"];
[self.arrayContentData addObject:#"6.html"];
[self.arrayContentData addObject:#"1.html"];
[self.arrayContentData addObject:#"2.html"];
[self.arrayContentData addObject:#"3.html"];
[self.arrayContentData addObject:#"4.html"];
[self.arrayContentData addObject:#"5.html"];
[self.arrayContentData addObject:#"6.html"];
}
#pragma mark -
#pragma mark Get Filename from Document Directory
- (NSURLRequest *)getPageFromDocumentsDirectory:(NSString *)pstrPageName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *yourFilePath = [NSString stringWithFormat:#"%#/Html/%#", documentDirectory, pstrPageName];
NSURL *url = [NSURL fileURLWithPath:yourFilePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
return requestObj;
}
#pragma mark -
#pragma mark ScrollView Methods
-(void)initiateScrollView{
views = [[NSMutableArray alloc] initWithCapacity:[self.arrayContentData count]];
NSMutableArray *controllers = [[NSMutableArray alloc] init];
for (unsigned i = 0; i < [self.arrayContentData count]; i++) {
[controllers addObject:[NSNull null]];
}
self.viewControllers = controllers;
[controllers release];
scrollView.contentSize = CGSizeMake([self.arrayContentData count]*scrollView.bounds.size.width,
scrollView.bounds.size.height);
scrollView.delegate = self;
if(self.intCurrIndex == 0){
[self loadScrollViewWithPage:self.intCurrIndex];
}
}
-(void)loadScrollViewWithPage:(int)page{
if (page < 0) return;
if (page >= [self.arrayContentData count]) return;
// replace the placeholder if necessary
NSString *strContentName = [self.arrayContentData objectAtIndex:page];
//UIImageView *controller = [viewControllers objectAtIndex:page];
UIWebView *controller = [viewControllers objectAtIndex:page];
if ((NSNull *)controller == [NSNull null]) {
UIView *v = [[UIView alloc] initWithFrame:scrollView.bounds];
v.backgroundColor = [UIColor colorWithHue:arc4random()/(float)0x100000000
saturation:0.75
brightness:1.0
alpha:1.0];
controller = [[UIWebView alloc] initWithFrame:v.bounds];
controller.delegate = self;
controller.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
controller.center = CGPointMake(v.bounds.size.width/2, v.bounds.size.height/2);
[controller loadRequest:[self getPageFromDocumentsDirectory:strContentName]];
[v addSubview:controller];
[controller release];
[scrollView addSubview:v];
[views addObject:v];
[viewControllers replaceObjectAtIndex:page withObject:controller];
[v release];
}
[self alignSubviews];
/*
// add the controller's view to the scroll view
if (nil == controller.superview) {
CGRect frame = scrollView.frame;
frame.origin.x = frame.size.width * page;
//frame.origin.y = 0;
controller.frame = frame;
[scrollView addSubview:controller];
}*/
}
-(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 (self.bolPageControlUsed) {
// 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
currentPage = scrollView.contentOffset.x / scrollView.bounds.size.width;
[self loadScrollViewWithPage:currentPage];
}
// At the end of scroll animation, reset the boolean used when scrolls originate from the UIPageControl
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
self.bolPageControlUsed = NO;
}
#pragma mark -
#pragma mark setUp ScrollView
- (void)setUpScrollView {
// Set up some colorful content views
views = [[NSMutableArray alloc] initWithCapacity:[self.arrayContentData count]];
for (int i = 0; i < [self.arrayContentData count]; i++) {
UIView *v = [[UIView alloc] initWithFrame:scrollView.bounds];
v.backgroundColor = [UIColor colorWithHue:arc4random()/(float)0x100000000
saturation:0.75
brightness:1.0
alpha:1.0];
NSString *strContentName = [self.arrayContentData objectAtIndex:i];
UIWebView *controller = [[UIWebView alloc] initWithFrame:v.bounds];
controller.delegate = self;
controller.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
controller.center = CGPointMake(v.bounds.size.width/2, v.bounds.size.height/2);
[controller loadRequest:[self getPageFromDocumentsDirectory:strContentName]];
[v addSubview:controller];
[controller release];
[scrollView addSubview:v];
[views addObject:v];
[v release];
}
[self alignSubviews];
[scrollView flashScrollIndicators];
}
#pragma mark -
#pragma mark Align Scroll Subviews
- (void)alignSubviews {
// Position all the content views at their respective page positions
scrollView.contentSize = CGSizeMake([self.arrayContentData count]*scrollView.bounds.size.width,
scrollView.bounds.size.height);
NSUInteger i = 0;
for (UIView *v in views) {
v.frame = CGRectMake(i * scrollView.bounds.size.width, 0,
scrollView.bounds.size.width, scrollView.bounds.size.height);
for (UIWebView *w in v.subviews) {
[w setFrame:v.bounds];
}
i++;
}
}
#pragma mark -
#pragma mark UIWebView delegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
}
#pragma mark -
#pragma mark Orientation
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return YES;
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration {
currentPage = scrollView.contentOffset.x / scrollView.bounds.size.width;
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
duration:(NSTimeInterval)duration {
[self alignSubviews];
//NSLog(#"%f", currentPage * scrollView.bounds.size.width);
scrollView.contentOffset = CGPointMake(currentPage * scrollView.bounds.size.width, 0);
}
I hope, it will be helpful to all.
Cheers.

Is it necessary to have a separate UIViewController (PageViewController) for every page in your UIScrollView? Why not let your MainViewController take care of this.
Resizing your views (and your UI in general) after rotating the device is much easier when you build your UI in Interface Builder.

I'm not absolutely sure I understand you right.. however, some thoughts:
The frame property is one thing (A), how the view contents are displayed in there is another (B). The frame CGRect is the (theoretical) boundary of your view in the superview (parent view) .. however, your View does not necessarily need to fill that whole frame area.
Regarding (A):
Here we have the UIView's autoresizingMask property to set how the frame is resized when the superview is resized. Which happens when you change the orientation. However, you can usually rely on the default settings (worked for me so far).
Regarding (B):
How the view contents are distributet in the view frame is specified by UIView's property contentMode. With this property, you can set that the aspect ratio needs to stay intact. Set it to UIViewContentModeScaleAspectFit for example, or something else..
see here:
http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW99
PS: I wrote "theoretical", because your view contents may also exceed those frame boundaries - they are only limiting the view when UIView's clipsToBounds property is set to YES. I think it's a mistake that Apple set this to NO by default.

In addition to what Efrain wrote, note that the frame property IS NOT VALID if the view transform is other than the identity transform -- i.e., when the view is rotated.
Of course, you accounted for the fact that your views need to be at a new offset position, right?

Related

UITableViewCell UITapGestureRecognizer not responding

I am a beginner with Objective-C and I am working on existing code base.
In the following code, UITapGestureRecognizer doesn't seem to trigger tap method. I have tried adding
[self setUserInteractionEnabled:YES];
Can anyone help me figure out what is not working here.
This is my UITableViewCell implementation class:
#interface ELCAssetCell ()
#property(nonatomic, strong) NSArray * rowAssets;
#property(nonatomic, strong) NSMutableArray * rowViews;
#end
#implementation ELCAssetCell
#synthesize rowAssets;
- (id)initWithReuseIdentifier:(NSString *)_identifier cellWidth:(CGFloat)width {
if (self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:_identifier]) {
self.rowViews = [[NSMutableArray alloc] init];
for (int i = 0; i < 4; i++) {
[self.rowViews addObject:[[AssetView alloc] initWithFrame:CGRectZero]];
}
for (AssetView * view in self.rowViews) {
[self addSubview:view];
}
_width = width;
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
CGFloat itemWidth = _width / 4;
CGRect frame = CGRectMake(2, 2, itemWidth - 4, itemWidth - 4);
for (AssetView * view in self.rowViews) {
[view setFrame:frame];
[[view gestureRecognizers] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL
*stop) {
[view removeGestureRecognizer:obj];
}];
[view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(tap:)]];
frame.origin.x += itemWidth;
}
}
- (void)tap:(UITapGestureRecognizer *)gest {
[self.delegate assetPressed:[(AssetView *)[gest view] asset]];
[(AssetView *)[gest view] toggleSelection];
}
#end
The most likely problem is that you are adding the views to the cell itself -- they should be added to the cell's contentView.
Change:
for (AssetView * view in self.rowViews) {
[self addSubview:view];
}
to:
for (AssetView * view in self.rowViews) {
[self.contentView addSubview:view];
}
Aside from that, this looks absolutely terrible!
you should be using auto-layout instead of setting frames
layoutSubviews can be called multiple times... you should be adding the UITapGestureRecognizer when you create the views, not removing / re-adding every time layoutSubviews is called.

Add image to UISegmentedControl from another controller

MainViewController contains UISegmentedControl with 3 segments.
SliderSubViewController contains a UISlider and -(void) sliderValueChanged:(UISlider*)sender
I want to add a code like this in SliderSubViewController.m but I'm stuck on how to access the UISegmentedControl and add an image:
- (void)viewDidLoad
{
[super viewDidLoad];
mainController = [[MainViewController alloc] initWithNibName:nil bundle:nil];
[minPrisSlider addTarget:self
action:#selector(sliderValueChanged:)
forControlEvents:UIControlEventValueChanged];
- (void)sliderValueChanged:(UISlider*)sender
{
NSUInteger index = (NSUInteger)(minPrisSlider.value + 0.5); // Round the number.
[minPrisSlider setValue:index animated:NO];
int progressAsInt =(int)(minPrisSlider.value + 0.5f);
NSString *newText =[[NSString alloc] initWithFormat:#"%d,-",progressAsInt];
minPrisText.text = newText;
if (minPrisSlider.value != 70) {
/*mainController.segmentedControl add main bundle image named "CheckboxChecked.png"
to current segment*/
}
}
If you have added SliderViewController as subview on MainViewController, One approach you can try is to just declare object of MainViewController in SliderViewController write #property and #synthesize, dont allocate it and while adding SliderView as subview just assign it as
sliderviewcontrollerObject.mainViewControllerObject = self;
now you can access segmentedControl from sliderview ass self.mainViewControllerObject.segmentedbar
Also you can try delegate approach.

UIImageView added to an NSArray doesn't respond

I am fairly new to Objective-C, this is the first time I really don't know what to do.
I have a class - Parser - which creates UIImageViews, inits them with images and adds them to the UIView. The class also adds these UIImageViews to NSMutableArray - imgArray, which is a property of another class - Page.
Then, on the click of a button, I call the Page class from a Manager class, loop through the imgArray and try to set a new images for the UIImageViews in the array.
It doesn't work. Actually nothing I do to the UIImageViews doesn't work.
I try [img removeFromSuperView], [img setHidden:YES] and more. It doesn't response.
Here I declare the Array property in Page:
#property (nonatomic, retain) NSMutableArray *imgArray;
Here is the code from Parser where I create the image and add it to the array:
UIImageView *img = [[UIImageView alloc] initWithFrame: frame];
NSString *name = [c imageSource];
[img setImage: [UIImage imageFromBook: name]];
[view addSubview: img];
[c setImage:img];
if (!page.imgArray)
{
page.imgArray = [[NSMutableArray alloc] init];
}
[page.imgArray addObject:img];
[img release];
Here is the loop code from the Manager:
- (void) set3D:(bool)is3D
{
Page *page = [[DataManager data] currentPage];
int count = [page.imgArray count];
for (int i = 0; i < count; i++)
{
UIImageView *img = [page.imgArray objectAtIndex:i];
[img setImage:[UIImage imageNamed:image3DSource]];
}
}
Thanks in advance for any help!
There is no need to store the UIImageView's in an array.
When the UIImageView's are created, you can tag them with an arbitrary number, like.
#define K_MIN_IMGV 100
#define K_MAX_IMGV 120
- (void) setupViews
{
for (NSInteger count = K_MIN_IMGV; count < K_MAX_IMGV; ++count)
{
UIImageView *imgV = // create image view, set properties
imgV.tag = count; // tag the views for easy retrieval later
...
[mainView addSubview: imgV]; // add subviews
[imgV release], imgV = nil; // mainView now manages, release our allocation
}
}
// how to set new images
- (void) setupNewImages
{
for (NSInteger count = K_MIN_IMGV; count < K_MAX_IMGV; ++count)
{
UIImageView *imgV = (UIImageView *) [mainView viewWithTag: count]; // retrieve imageView
[imgV setImage: newImage]; // set new image
}
}
// To remove the imageView, you can use
UIImageView *imgV = (UIImageView *) [mainView viewWithTag: 123];
[imgV removeFromSuperview];
Have you tried to enumerate through the array using:
for(UIImageView* imageView in page.imgArray)
{
//Do code
}
This will tell you if there any imageViews in page.imgArray.
How are you adding objects to NSMutableArray and how are you initialising your NSMutableArray.
I remember having a problem adding objects to NSMutableArray but setting my init to solved this:
NSMutableArray* mutableArray = [NSMutableArray array];
Also what properties have you set on imgArray in page? Are you retaining the values?
Need to see more code to gain a fuller understanding.

How can I display my images in my viewController the same as the below screen shot?

In my iPad program I have an array which holds images. How can I display my all images (from an image array) in my viewController the same as the below screen shot? Is there a good way to do it, any sample application paths to refer or sample code?
I need the following functionality.
Tapping an image will show it full screen
A close button to close this view as the same as the screen shot.
Two buttons to display the remaining and previous images.
A sample screen shot is attached below. We can see that the below application is showing all images at the right side of the screen.
Alright, this should be easy, though a bit of coding is needed.
Start out with a simple view based app template.
I don't know where the images come from so I just put all the images to be shown in the resources folder.
The view controller PictureViewController will accept an array of UIImages and should be presented modally. I'll post the code below.
The code to show the PictureViewController is placed in the view controller created by the template. I just added a simple UIButton to the view to trigger an action which looks something like this:
- (IBAction)onShowPictures
{
// Load all images from the bundle, I added 14 images, named 01.jpg ... 14.jpg
NSMutableArray *images = [NSMutableArray array];
for (int i = 1; i <= 14; i++) {
[images addObject:[UIImage imageNamed:[NSString stringWithFormat:#"%02d.jpg", i]]];
}
PictureViewController *picViewController = [[PictureViewController alloc] initWithImages:images];
[self presentModalViewController:picViewController animated:YES];
[picViewController release];
}
The view controller's view was created with interface builder, looking like this:
PictureViewController.xib
View Hierarchy
The fullscreen image is linked to an outlet fullScreenImage seen in the following header file. Actions are connected as well.
I've set the fullscreen imageView's content mode to Aspect Fit.
The Thumbnails will be added dynamically with code. Here's the view controller's code
PictureViewController.h
#interface PictureViewController : UIViewController
{
NSMutableArray *imageViews;
NSArray *images;
UIImageView *fullScreenImage;
int currentPage;
}
#property (nonatomic, retain) NSMutableArray *imageViews;
#property (nonatomic, retain) NSArray *images;
#property (nonatomic, retain) IBOutlet UIImageView *fullScreenImage;
- (id)initWithImages:(NSArray *)images;
- (IBAction)onClose;
- (IBAction)onNextThumbnails;
- (IBAction)onPreviousThumbnails;
#end
PictureViewController.m
The define MAX_THUMBNAILS on top defines the maximum of thumbnails seen. A UITapGestureRecognizer will take care of the tap events for the thumbnails. Adjust the CGRectMake in setupThumbnailImageViews to position the thumbnails as you wish. This controller is just a basic approach without orientation support.
#import "PictureViewController.h"
#define MAX_THUMBNAILS 6
#interface PictureViewController ()
- (void)showSelectedImageFullscreen:(UITapGestureRecognizer *)gestureRecognizer;
- (void)setupThumbnailImageViews;
- (void)setThumbnailsForPage:(int)aPage;
- (UIImage *)imageForIndex:(int)anIndex;
#end
#implementation PictureViewController
#synthesize imageViews, images, fullScreenImage;
- (id)initWithImages:(NSArray *)someImages
{
self = [super init];
if (self) {
self.images = someImages;
self.imageViews = [NSMutableArray array];
currentPage = 0;
}
return self;
}
- (void)viewDidLoad
{
self.fullScreenImage.image = [images objectAtIndex:0];
[self setupThumbnailImageViews];
[self setThumbnailsForPage:0];
}
- (void)showSelectedImageFullscreen:(UITapGestureRecognizer *)gestureRecognizer
{
UIImageView *tappedImageView = (UIImageView *)[gestureRecognizer view];
fullScreenImage.image = tappedImageView.image;
}
- (void)setupThumbnailImageViews
{
for (int i = 0; i < MAX_THUMBNAILS; i++) {
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20.0,
166.0 + (130.0 * i),
130.0,
90.0)];
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
action:#selector(showSelectedImageFullscreen:)];
tapGestureRecognizer.numberOfTapsRequired = 1;
tapGestureRecognizer.numberOfTouchesRequired = 1;
[imageView addGestureRecognizer:tapGestureRecognizer];
[tapGestureRecognizer release];
imageView.userInteractionEnabled = YES;
[imageViews addObject:imageView];
[self.view addSubview:imageView];
}
}
- (void)setThumbnailsForPage:(int)aPage
{
for (int i = 0; i < MAX_THUMBNAILS; i++) {
UIImageView *imageView = (UIImageView *)[imageViews objectAtIndex:i];
UIImage *image = [self imageForIndex:aPage * MAX_THUMBNAILS + i];
if (image) {
imageView.image = image;
imageView.hidden = NO;
} else {
imageView.hidden = YES;
}
}
}
- (UIImage *)imageForIndex:(int)anIndex
{
if (anIndex < [images count]) {
return [images objectAtIndex:anIndex];
} else {
return nil;
}
}
#pragma mark -
#pragma mark user interface interaction
- (IBAction)onClose
{
[self dismissModalViewControllerAnimated:YES];
}
- (IBAction)onNextThumbnails
{
if (currentPage + 1 <= [images count] / MAX_THUMBNAILS) {
currentPage++;
[self setThumbnailsForPage:currentPage];
}
}
- (IBAction)onPreviousThumbnails
{
if (currentPage - 1 >= 0) {
currentPage--;
[self setThumbnailsForPage:currentPage];
}
}
#pragma mark -
#pragma mark memory management
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
[images release];
}
- (void)viewDidUnload
{
[super viewDidUnload];
[imageViews release];
[fullScreenImage release];
}
- (void)dealloc
{
[images release];
[imageViews release];
[fullScreenImage release];
[super dealloc];
}
#end
The result:

Why is my UIPickerView not animating like it should be?

so this is basically like a slot machine type thing, very basic, but the problem Im having is that when you click the spin button the movement of the components is not animated, even though i have sent the animated argument a YES BOOL. I have no idea what I am doing wrong, any help would be appreciated.
Nick
ps download the entire project here: http://files.me.com/knyck2/dcca9y
//
// CustomPickerViewController.m
// Pickers
//
// Created by Nicholas Iannone on 1/29/10.
// Copyright 2010 Apple Inc. All rights reserved.
//
#import "CustomPickerViewController.h"
#implementation CustomPickerViewController
#synthesize column1, column2, column3, column4, column5, picker, winLabel;
-(IBAction) spin : (id) sender {
NSLog(#"even got here");
BOOL win = NO;
int numInRow = 1;
int lastVal = -1;
for (int i = 0; 1 < 5; i++) {
int newValue = random() % [self.column1 count];
if (newValue == lastVal) {
NSLog(#"even got here");
numInRow++;
}
else
numInRow = 1;
lastVal = newValue;
[picker selectRow:newValue inComponent:i animated:YES];
[picker reloadComponent:i];
if (numInRow >= 3)
win = YES;
NSLog(#"even got here");
}
if (win)
winLabel.text = #"winner!";
else {
winLabel.text = #"";
NSLog(#"even got here");
}
}
/*
// The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
UIImage *seven = [UIImage imageNamed:#"seven.png"];
UIImage *bar = [UIImage imageNamed:#"bar.png"];
UIImage *crown = [UIImage imageNamed:#"crown.png"];
UIImage *cherry = [UIImage imageNamed:#"cherry.png"];
UIImage *lemon = [UIImage imageNamed:#"lemon.png"];
UIImage *apple = [UIImage imageNamed:#"apple.png"];
for (int i = 1; i <= 5 ; i++) {
UIImageView *sevenView = [[UIImageView alloc] initWithImage: seven];
UIImageView *barView = [[UIImageView alloc] initWithImage: bar];
UIImageView *crownView = [[UIImageView alloc] initWithImage: crown];
UIImageView *cherryView = [[UIImageView alloc] initWithImage: cherry];
UIImageView *lemonView = [[UIImageView alloc] initWithImage: lemon];
UIImageView *appleView = [[UIImageView alloc] initWithImage: apple];
NSArray *imageViewArray = [[NSArray alloc] initWithObjects: sevenView, barView, crownView, cherryView, lemonView, appleView, nil];
NSString *fieldName =[[NSString alloc] initWithFormat:#"column%d", i];
[self setValue:imageViewArray forKey:fieldName];
[fieldName release];
[imageViewArray release];
[sevenView release];
[crownView release];
[barView release];
[cherryView release];
[lemonView release];
[appleView release];
}
srandom(time(NULL));
[super viewDidLoad];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[picker release];
[winLabel release];
[column1 release];
[column2 release];
[column3 release];
[column4 release];
[column5 release];
[super dealloc];
}
#pragma mark -
#pragma mark Picker Data Source Methods
-(NSInteger) numberOfComponentsInPickerView: (UIPickerView *) pickerView {
return 5;
}
-(NSInteger) pickerView: (UIPickerView *) pickerView numberOfRowsInComponent: (NSInteger) component {
return [self.column1 count];
}
#pragma mark Picker Delegate Methods
-(UIView *) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent: (NSInteger) component reusingView : (UIView *)view {
NSString *arrayName = [[NSString alloc] initWithFormat:#"column%d", component + 1];
NSArray *array = [self valueForKey:arrayName];
NSLog(#"got here yo");
return [array objectAtIndex: row];
NSLog(#"holyshit");
}
#end
I went back and compared my code to the book that this project is listed in and I noticed that my code would perform as expected (with animation) if I were to build into a 3.1.2 sdk and iphone sim. So something in the new xcode is skanking the animation, at least that is the way it appears.
It's probably not animating because you do [picker reloadComponent:i] right after selecting a row with animation. Reloading probably causes any animation to stop, and shouldn't be necessary since you're not actually changing the contents of the picker.