Shuffle the positions of a row of buttons in a UIView - iphone

I have a word,depending on its length,I create buttons assigning a character from the word randomly.I am presenting the shuffled character button arrangement in a row.Now I would like to sort the positions of those buttons,i.e. 1st to 3rd,3rd to 5th and so on.Please note that the number of buttons are not fixed,they vary depending on word length.Here is the sample code snippet for an understanding of how I create buttons.
-(void)buttonsCreation:(int)noOfButtons
{
NSMutableArray *charactersArray = [NSMutableArray array];
self.wordButtons = [[NSMutableArray alloc]initWithCapacity:30];
BOOL record = NO;
int randomNumber;
self.jumbledWord = [jumbledWord stringByReplacingOccurrencesOfString:#" " withString:#""];
for (int i=0; [charactersArray count] < jumbledWord.length; i++) //Loop for generate different random values
{
randomNumber = arc4random() % jumbledWord.length;//generating random number
if(i==0)
{
[charactersArray addObject:[NSNumber numberWithInt:randomNumber]];
}
else
{
for (int j=0; j<= [charactersArray count]-1; j++)
{
if (randomNumber ==[[charactersArray objectAtIndex:j] intValue])
record = YES;
}
if (record == YES)
record = NO;
else
[charactersArray addObject:[NSNumber numberWithInt:randomNumber]];
}
}
int arrayValue;
float x;
float y;
if ([jumbledWord length]>11)
{
int remainingWordslength = [jumbledWord length]-11;
x = ((475/2) - (38.0 *(11/2.0))) + 8;
y = ((475/2) - (38.0 *(remainingWordslength/2.0))) + 8;
}
else
{
x = ((475/2) - (38.0 *([jumbledWord length]/2.0))) + 8;
}
for(int i=0;i<[jumbledWord length];i++)
{
CGFloat translation = 0.0;
if(i>=0 && i<11)
{
arrayValue = [[charactersArray objectAtIndex:i] intValue];
UIButton *characterButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
characterButton.frame = CGRectMake(x,160.0, 35.0, 35.0);
x = x + 38;
if (jumbledWord.length>=1 && jumbledWord.length<5)
{
translation = (self.view.frame.size.width - characterButton.frame.size.width)+65.0;
}
if (jumbledWord.length>=5 && jumbledWord.length<11)
{
translation = (self.view.frame.size.width - characterButton.frame.size.width)+160.0;
}
characterButton.transform = CGAffineTransformMakeTranslation(translation, 0);
[UIView animateWithDuration:1.30f
delay:0.7
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^{
characterButton.transform = CGAffineTransformIdentity;
} completion:^(BOOL finished) {
}];
[wordButtons addObject:characterButton];
NSString *characterValue = [NSString stringWithFormat:#"%c",[jumbledWord characterAtIndex:arrayValue]];
[characterButton setTitle:characterValue forState:UIControlStateNormal];
[characterButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
if (arrayValue==0)
{
arrayValue = 100;
}
[characterButton setTag:arrayValue*100];
[self.view addSubview:characterButton];
}
else if(i>=11 && i<20)
{
arrayValue = [[charactersArray objectAtIndex:i] intValue];
UIButton *characterButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
characterButton.frame = CGRectMake(y,200.0, 35.0, 35.0);
y = y + 38;
if (jumbledWord.length>=11 && jumbledWord.length<15)
{
translation = (self.view.frame.size.width - characterButton.frame.size.width)+70.0;
}
if (jumbledWord.length>=15 && jumbledWord.length<=20)
{
translation = (self.view.frame.size.width - characterButton.frame.size.width)+150.0;
}
characterButton.transform = CGAffineTransformMakeTranslation(translation, 0);
[UIView animateWithDuration:1.30f
delay:0.7
options:UIViewAnimationOptionTransitionFlipFromRight
animations:^{
characterButton.transform = CGAffineTransformIdentity;
} completion:^(BOOL finished) {
}];
[wordButtons addObject:characterButton];
NSString *characterValue = [NSString stringWithFormat:#"%c",[jumbledWord characterAtIndex:arrayValue]];
[characterButton setTitle:characterValue forState:UIControlStateNormal];
[characterButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
if (arrayValue==0)
{
arrayValue = 100;
}
[characterButton setTag:arrayValue*100];
[self.view addSubview:characterButton];
}
}
}
I do acknowledge the ideal choice would be to assign the frame i.e. "x" positions for buttons,but how do I do this.The other option being exchanging the index positions and I tried it too,i.e.:
-(void)shuffleButtons
{
for (UIButton *characterButton in wordButtons)
{
id sortObject1 = [self.wordButtons objectAtIndex:0];
id sortObject1 = [self.wordButtons objectAtIndex:1];
id sortObject1 = [self.wordButtons objectAtIndex:2];
[self.wordButtons removeObjectAtIndex:0];
[self.wordButtons removeObjectAtIndex:1];
[self.wordButtons insertObject:characterButton atIndex:1];
[self.wordButtons insertObject:characterButton atIndex:0];
[self.wordButtons removeObjectAtIndex:2];
[self.wordButtons insertObject:characterButton atIndex:1];
}
}
OOPS and it crashes,any one please guide me a way.I need to accomplish because there is an option for user to shuffle the jumbled arrangement of a word.
Thanks in advance :)

I've already developed a sample project for this.
Take a look at DragME source over github.

Since we are having all the buttons in wordButtons array,we can make use of those index locations and exchange their places with a little animation ;) ,i.e.
- (void)exchangeButtons
{
UIButton *firstButton = self.wordButtons[0];
UIButton *lastButton = self.wordButtons[self.wordButtons.count - 1];
UIButton *secondButton = self.wordButtons[1];
UIButton *thirdButton = self.wordButtons[2];
[self exchangeButton:firstButton withAnother:lastButton];
[self exchangeButton:secondButton withAnother:thirdButton];
}
//Animate buttons while interchanging positions
- (void)exchangeButton:(UIButton *)firstButton withAnother:(UIButton *)secondButton
{
CGRect firstButtonFrame = firstButton.frame; [UIView animateWithDuration:1.0f animations:^{ firstButton.frame = secondButton.frame; secondButton.frame = firstButtonFrame; }];
}
Please note that the exchange button code may vary,it all depends on the length of word i.e. number of buttons.So you may place conditions like if(wordButtons.count >= 6) or >=10 etc. before you exchange the button indices.
P.S. -- A more effective and non-hard coded solution
Let's store the frame of the button while creating a row of buttons and use that to interchange the button positions i.e. while creation assign our button frame to declared CGRect object,i.e.
CGRect originalFrameArray[16]; --> **Global variable**
originalFrameArray[i] = characterButton.frame;
Now let's create 2 arrays,one for shuffling the word and storing the character buttons indices,other for modifying the buttons array and then start exchanging the buttons with little animation :)
- (void)exchangeButtons
{
NSMutableArray *charactersArray = [NSMutableArray array];
NSMutableArray *copyOfButtons = [NSMutableArray arrayWithArray:wordButtons];
BOOL record = NO;
int randomNumber;
for (int i=0; [charactersArray count] < jumbledWord.length; i++) //Loop for generate different random values
{
randomNumber = arc4random() % jumbledWord.length;//generating random number
if(i==0)
{
[charactersArray addObject:[NSNumber numberWithInt:randomNumber]];
}
else
{
for (int j=0; j<= [charactersArray count]-1; j++)
{
if (randomNumber ==[[charactersArray objectAtIndex:j] intValue])
record = YES;
}
if (record == YES)
record = NO;
else
[charactersArray addObject:[NSNumber numberWithInt:randomNumber]];
}
}
int arrayValue;
for(int i=0;i<[jumbledWord length];i++)
{
arrayValue = [[charactersArray objectAtIndex:i] intValue];
[wordButtons replaceObjectAtIndex:arrayValue withObject:[copyOfButtons objectAtIndex:i]];
}
for(int i=0; i < [jumbledWord length]; i++)
{
UIButton *characterButton = [wordButtons objectAtIndex:i];
[self shiftButtonToFrame:characterButton :originalFrameArray[i]];
}
}
//Animate the buttons while they exchange positions
- (void) shiftButtonToFrame:(UIButton *) characterButton :(CGRect) frame
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:1.0];
[characterButton setFrame:frame];
[UIView commitAnimations];
}
Hope it helps some one.Thanks and happy coding :)

Related

Need to create photo slider using photo library photos in iphone

I want photo slider like whts app has. It should access all the pics or some of the pics from in build photo library and it should be scrollable using scroll view.
I have tried with different photo viewer but everything has memory issue. So not sure if anyone has it's working solution. Really appreciate your help.
Thank you,
Ankita
This is working almost fine, but one small problem with backbord direction scrolling. Just try this out may be you can find some direction to go and may be find better solution using it.
(Have used ELCImagePicker to show first time all images and then on selecting one present the scrollview to show large images at a time 10 images are shown also have tweak the delegate method of ELCImagePickerController to get the index of selected image)
At first load ie when select image from ELCImagePickerController
- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info selectedIndex:(NSInteger)_index {
[self dismissModalViewControllerAnimated:NO];
for (UIView *v in [scrollview subviews]) {
[v removeFromSuperview];
}
infoItems = [[NSArray alloc]initWithArray:info];
CGRect workingFrame = scrollview.frame;
workingFrame.origin.x = 0;
int indexFrame = picker.selectedIndex;
newIndex = indexFrame;
for(int i = 0; i < [info count]; i++)
{
NSDictionary *dict = [info objectAtIndex:i];
UIImageView *imageview = [[UIImageView alloc] initWithImage:[dict objectForKey:UIImagePickerControllerOriginalImage]];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
imageview.frame = workingFrame;
imageview.tag = i;
if(i >= indexFrame && i <= indexFrame + 9)
{
[scrollview addSubview:imageview];
workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
}
}
[scrollview setPagingEnabled:YES];
[scrollview setContentSize:CGSizeMake(workingFrame.origin.x, workingFrame.size.height)];
[scrollview scrollRectToVisible:CGRectMake(0, 0, workingFrame.size.width, workingFrame.size.height) animated:NO];
self.scrollview.hidden = NO;
self.pageControll.hidden = NO;
self.pageControll.numberOfPages = [[scrollview subviews]count];
index = 0;
lastContentOffset = scrollview.contentOffset.x;
NSLog(#"lastContentOffset %.2f",lastContentOffset);
}
After that on scrollViews delegate method
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
NSLog(#"ScrollViewDidEndDecelerating is called with subview(s) %d",[[scrollview subviews]count]);
if(lastContentOffset < scrollView.contentOffset.x)
{
index += (int)(scrollview.contentOffset.x - lastContentOffset)/scrollview.frame.size.width;
newIndex += (int)(scrollview.contentOffset.x - lastContentOffset)/scrollview.frame.size.width;
self.pageControll.currentPage = index;
NSLog(#"Index incremented %d \n newIndex %d",index,newIndex);
if(index == [[scrollView subviews]count]-1)
{
if(newIndex < [infoItems count]-1)
{
[self performSelector:#selector(reloadScrollViewWithNewImages)];
}
}
[Appirater userDidSignificantEvent:YES];
}
else if(lastContentOffset > scrollView.contentOffset.x)
{
index -= (int)(lastContentOffset - scrollview.contentOffset.x)/scrollview.frame.size.width;
newIndex -= (int)(int)(lastContentOffset - scrollview.contentOffset.x)/scrollview.frame.size.width;
self.pageControll.currentPage = index;
NSLog(#"Index decremented %d \n newIndex %d",index,newIndex);
if(index == 0)
{
if(newIndex > 0)
{
newIndex -= 9;
if(newIndex < 0)
newIndex = 0;
[self performSelector:#selector(reloadScrollViewWithNewImages)];
}
}
[Appirater userDidSignificantEvent:YES];
}
lastContentOffset = scrollView.contentOffset.x;
NSLog(#"New lastContentOffset %.2f",lastContentOffset);
}
and the method used for reload the scrollView is as follow
-(void)reloadScrollViewWithNewImages
{
for (UIView *v in [scrollview subviews]) {
[v removeFromSuperview];
}
CGRect workingFrame = scrollview.frame;
workingFrame.origin.x = 0;
NSLog(#"reloadScrollView newIndex %d",newIndex);
int indexFrame = newIndex;
for(int i = 0; i < [infoItems count]; i++)
{
NSDictionary *dict = [infoItems objectAtIndex:i];
UIImageView *imageview = [[UIImageView alloc] initWithImage:[dict objectForKey:UIImagePickerControllerOriginalImage]];
[imageview setContentMode:UIViewContentModeScaleAspectFit];
imageview.frame = workingFrame;
imageview.tag = i;
if(i >= indexFrame && i <= indexFrame + 9)
{
[scrollview addSubview:imageview];
workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width;
}
}
[scrollview setPagingEnabled:YES];
[scrollview setContentSize:CGSizeMake(workingFrame.origin.x, workingFrame.size.height)];
[scrollview scrollRectToVisible:CGRectMake(0, 0, workingFrame.size.width, workingFrame.size.height) animated:NO];
self.scrollview.hidden = NO;
self.pageControll.hidden = NO;
index = 0;
self.pageControll.numberOfPages = [[scrollview subviews]count];
NSLog(#"number %d",[[scrollview subviews]count]);
lastContentOffset = scrollview.contentOffset.x;
NSLog(#"reloadScrollView's lastContentOffset %.2f",lastContentOffset);
}
and all used properties and private ivars declared in .h file's interface part required in this code are
Private ivars
NSInteger index;
float lastContentOffset;
Properties
#property (nonatomic,strong) IBOutlet UIScrollView *scrollview;
#property (strong, nonatomic) NSArray *infoItems;
#property (assign, atomic) int newIndex;
Happy Coding :)
You can use CATiledLayer to draw image. CATiledLayer can be used to increase the performance of paging, panning, and zooming with high-resolution images or large sets of photos.
As i commented above you can go by reusable view approach means at a time only three imagview or view will be in memory. Let say you are showing photo number:2 so, you should have to keep photo:1,2 and3 in memory(i.e. to avoid flicker) no need to load all photos at a time. Suppose you are scrolling to photo number:3 then your logic should discard photo number:1 and should load photo number:2,3,4. If you are still not getting or don't know how to do this programmatically then don't worry. Apple's good sample code is available that is doing all you want.
Sample code
In above sample code they have displayed two way of displaying image.
One is directly showing/setting the image into image view.
Second is with drawing image with TileView using this method: - (void)displayTiledImageNamed:(NSString *)imageName size:(CGSize)imageSize
If you are thinking lot of about memory then definitely you have to use second approach.

Kindle iPhone App Navigation - how to

I like the kindle for iPhone's navigation - the one which enables you to just slide the titles in the navigation bar to move from one view to another. (I'm attaching the image)
However, I was searching for a long time yesterday and I cannot find anybody who has done something similar.
Would you have any ideas on how to do this?
UPDATE: May 24, 2012
So now I have codes. Thanks to this tutorial http://bit.ly/xNOiqd. (I just copied most of his code.) But I still cannot achieve the same effect that the kindle app's nav bar has. I can now peek on the left and the right item but my scroll view skips the labels which are on the odd indices of my array. Let's say I have 'Favourites', 'All Products', and 'Categories'. When I swipe left, I move from 'Favourites' to 'Categories' and skip 'All Products'
Here's the code.
#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];
}
}
- (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.x = (frame.size.width /2) * page;
frame.origin.y = 0.0f;
//
frame = CGRectInset(frame, 10.0f, 0.0f);
//self.scrollView.bounds = frame;
/* == orig line
UIImageView *newPageView = [[UIImageView alloc] initWithImage:[self.pageImages objectAtIndex:page]];
newPageView.contentMode = UIViewContentModeScaleAspectFit;
newPageView.frame = frame;
*/
UILabel *newPageView = [[UILabel alloc] init];
newPageView.text = [self.pageImages objectAtIndex:page];
newPageView.textColor = [UIColor whiteColor];
//newPageView.textColor = [UIColor grayColor];
newPageView.textAlignment = UITextAlignmentCenter;
newPageView.font = [UIFont fontWithName:#"Helvetica-Bold" size:20];
[newPageView setBackgroundColor:[UIColor clearColor]];
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]];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
//scroll view stuff
self.scrollView.delegate = self;
//attempt to make size of scrollview smaller
//CGRect frame = self.scrollView.bounds;
//frame = CGRectInset(frame, 10.0f, 0.0f);
//CGFloat width = self.scrollView.frame.size.width/2.0f;
self.pageImages = [NSArray arrayWithObjects:#"Favourites", #"All Products", #"Categories",#"Boo yah", 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];
CGSize pagesScrollViewSize = self.scrollView.frame.size;
//self.scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * self.pageImages.count, pagesScrollViewSize.height);
//This modifies the size of the scroll view, I can't seem to get it right
self.scrollView.contentSize = CGSizeMake((pagesScrollViewSize.width / 1.50f )* self.pageImages.count, self.scrollView.frame.size.height);
// Load the initial set of pages that are on screen
[self loadVisiblePages];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
// Load the pages which are now on screen
[self loadVisiblePages];
}
iCarousel is a nice open source project with lots of scroll types.
A paged scrollview and AQGridView most likely. If not, it would be an acceptable reverse-engineering attempt anyways.

I want to perform the animation on the custom view cell in ios

I have an requirement like on taping on tableView cell it should animate and dropped (jumped)to trash icon.
Am using UIBezierPath to animate the text and jump function but I cant move the label which is inside the tableViewCell.
Any idea and suggestions would be highly appreciated.
Here check the below code so far I have done.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableArray *views=[[NSMutableArray alloc]init];
int i=0;
int j=indexPath.row;
UIView *anim = nil;
UIView *vi2;
for (UIView *theview in destination.superview.subviews)
{
// if (theview.tag != 2)
// continue;
NSLog(#"%#",theview);
if ([theview isKindOfClass:[UITableView class]])
{
// NSLog(#"%#",theview);
UIView *vi= theview;//(UITableView *)[UITableView class];
// NSLog(#"%#",vi);
// NSMutableArray *views=[[NSMutableArray alloc]init];
for(UIView *vi1 in vi.subviews )
{
NSLog(#" the current view....%#",vi1);
for (int k = 0; k < [arrayList count]; k++)
{
[views insertObject:vi1 atIndex:i++];
NSLog(#" ddddd %#",[views objectAtIndex:i-1]);
}
}
// vi1=(UITableViewCell*)[tableElements objectAtIndex:i];
anim=(UIView *)[views objectAtIndex:j];
anim = vi2;
for (int k = 0; k < [views count]; k++)
NSLog (#"Element %d = %#", k, [views objectAtIndex: k]);
break;
}
}
if (!anim)
return;
UIBezierPath *movePath = [UIBezierPath bezierPath];
[movePath moveToPoint:anim.center];
[movePath addQuadCurveToPoint:destination.center
controlPoint:CGPointMake(destination.center.x, anim.center.y)];
CAKeyframeAnimation *moveAnim = [CAKeyframeAnimation animationWithKeyPath:#"position"];
moveAnim.path = movePath.CGPath;
moveAnim.removedOnCompletion = YES;
CABasicAnimation *scaleAnim = [CABasicAnimation animationWithKeyPath:#"transform"];
scaleAnim.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
scaleAnim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)];
scaleAnim.removedOnCompletion = YES;
CABasicAnimation *opacityAnim = [CABasicAnimation animationWithKeyPath:#"alpha"];
opacityAnim.fromValue = [NSNumber numberWithFloat:1.0];
opacityAnim.toValue = [NSNumber numberWithFloat:0.1];
opacityAnim.removedOnCompletion = YES;
CAAnimationGroup *animGroup = [CAAnimationGroup animation];
animGroup.animations = [NSArray arrayWithObjects:moveAnim, scaleAnim, opacityAnim, nil];
animGroup.duration = 0.5;
[anim.layer addAnimation:animGroup forKey:nil];
}
Arun..
I can suggest to make snapshot of your cell and put it on the current main view in hierarchy (mostly it will self.view) as UIImageView. You delete you cell from table as is, but apply animation for that UIImageView. I've done this trick when tried to make drag-n-drop with UITableViews.

How to scroll characters on a label in Cocos2D?

I have a sprite on which there is a label (CCLabelTTF). On that label i have A,B,C,D,E, etc printed when they are clicked. I want them to scroll left. I've googled some tuorials but i am unable to find the solution and stuck here for long. Here is the screenshot of my game. You can see the characters from A to J. When i click on more incoming characters, that portion should scroll. What can i do to make the characters scroll?
Here is the code from which the characters are shown on label (lblSelectedAlpha) added on sprite:-
-(void)showSelectedAlphaBet{
fSelectedAlphaY =26;
if (tempBackground) {
[tempBackground removeFromParentAndCleanup:YES];
}
tempBackground = [CCSprite spriteWithFile:#"stripe_2.png"];
tempBackground.position = ccp(160,30);
[self addChild:tempBackground z:30];
for (int i=0; i<[arryAddSelectedChar count]; i++) {
// NSLog(#"[arryAddSelectedChar count] %#",[arryAddSelectedChar objectAtIndex:i]);
lblSelectedAlpha = [CCLabelTTF labelWithString:
[arryAddSelectedChar objectAtIndex:i]dimensions:CGSizeMake(30,30)
alignment:UITextAlignmentCenter fontName:#"Marker Felt" fontSize:30];
lblSelectedAlpha.position = ccp(fSelectedAlphaY,25);
lblSelectedAlpha.tag=i;
lblSelectedAlpha.color = ccc3(125,125,125);
[tempBackground addChild:lblSelectedAlpha z:5];
fSelectedAlphaY +=25;
}
}
Scrolling is simply a constant change in position over time. Basically something like this:
-(void) update:(ccTime)delta
{
label.position = CGPointMake(label.position.x - 1, label.position.y);
}
Well, this is how i implemented scrolling in my cocos2d game
// How to add scroll on label. This i did with a UITextView
// inside init, i took
{
scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(10,430, 150, 50)]
alphabetScroll = [[UITextView alloc] initWithFrame:CGRectMake(10,0,50 ,50)];
alphabetScroll.font = [UIFont fontWithName:#"verdana" size:30.0f];
alphabetScroll.backgroundColor = [UIColor clearColor];
alphabetScroll.textColor = [UIColor colorWithRed:125.0/255.0 green:125.0/255.0 blue:125.0/255.0 alpha:1.0f];
alphabetScroll.userInteractionEnabled=NO;
[scroll addSubview:alphabetScroll];
[[[CCDirector sharedDirector]openGLView]addSubview:scroll];
}
-(void)showSelectedAlphaBet
{
NSLog(#"showSelectedAlphaBet");
fSelectedAlphaY =26; // I have 26 alphabets
if (tempBackground) {
[tempBackground removeFromParentAndCleanup:YES];
}
// Area where alphabets are added on touch
tempBackground = [CCSprite spriteWithFile:#"stripe_2.png"];
tempBackground.position = ccp(160,30);
[self addChild:tempBackground z:30];
bottomAlphabet = #" ";
for (int i=0; i<[arryAddSelectedChar count]; i++) {
NSLog(#"[arryAddSelectedChar count] %#",[arryAddSelectedChar objectAtIndex:i]);
bottomAlphabet = [bottomAlphabet stringByAppendingString:[arryAddSelectedChar objectAtIndex:i]];
}
// Implementing shifting/scrolling
int newScrollViewWidth;
int newLabelWidth;
newScrollViewWidth =25*[arryAddSelectedChar count];
newLabelWidth =50*[arryAddSelectedChar count];
[scroll setContentSize:CGSizeMake(newScrollViewWidth, 45)];
alphabetScroll.frame = CGRectMake(0, 0, newLabelWidth, 45);
alphabetScroll.text = bottomAlphabet;
if (newScrollViewWidth > 150) {
CGPoint svos;
CGPoint pt;
svos = scroll.contentOffset;
CGRect rc = [alphabetScroll bounds];
rc = [alphabetScroll convertRect:rc toView:scroll];
pt = rc.origin;
pt.y = 0;
pt.x += 20*([arryAddSelectedChar count]-5);
[scroll setContentOffset:pt animated:YES];
}
}
// In dealloc
[alphabetScroll release];

animation of uiimageView stops

here is what I wanna do http://www.youtube.com/watch?v=rD3MTTPaK98
and here is my code:
-(void) onTimer {
UIImage * image = [UIImage imageNamed:#"abouffer_03.png"];
imageView = [[UIImageView alloc] initWithImage:image];
[imageView setCenter:[self randomPointSquare]];
[imageViewArray addObject:imageView];
[[self view] addSubview:imageView];
[imageView release];
ix=imageView.center.x;
iy=imageView.center.y;
X=(240-ix)/230;
Y=(160-iy)/230;
coteA=(240-ix);
coteB=(160-iy);
angleDeRotation=atan(coteB/coteA);
if(ix>250||0>iy>320){
imageView.transform = CGAffineTransformMakeRotation(angleDeRotation+3.14);
}
else{
imageView.transform = CGAffineTransformMakeRotation(angleDeRotation);
}
}
-(void)onTimer2{
for(int i=0; i< [imageViewArray count];i++){
imageView = [imageViewArray objectAtIndex:i];
imageView.center = CGPointMake(imageView.center.x + X, imageView.center.y + Y);
}
onTimer is called every 2 seconds
but it doesn't work, there is no error but when a "imageView" is created after 2 seconds it sop moving and go to the same direction of the new " imageView" that has been created. How can I solve this ? sorry for my english I'm french :/
You’re adding X and Y to all of your image views, but it’a always the last-computed value. Make an array of X and Y values and use the value that corresponds with your image view.
Where you define imageViewArray, also define xArray and yArray as NSMutableArrays. Then in -onTimer, when you set X and Y, do this:
[xArray addObject:[NSNumber numberWithFloat:X]];
[yArray addObject:[NSNumber numberWithFloat:Y]];
Finally, in -onTimer2, do this:
-(void)onTimer2{
for(int i=0; i< [imageViewArray count];i++) {
float localX = [(NSNumber *)[xArray objectAtIndex:i] floatValue];
float localY = [(NSNumber *)[yArray objectAtIndex:i] floatValue];
imageView = [imageViewArray objectAtIndex:i];
imageView.center = CGPointMake(imageView.center.x + localX, imageView.center.y + localY);
}
That will use the value of X and Y that you set in -onTimer.