- (IBAction)oneButton1:(id)sender - ios

I'm new to iOS, i want to update the text in ViewDidLoad() function.
This is my button function, When button is clicked animation take place and also adds the value "1" to "resultText.text"
- (IBAction)oneButton1:(id)sender {
oneBtn2.userInteractionEnabled = YES;
CGRect frame = oneBtn1.frame;
CGRect frame1 = reffButton.frame;
frame.origin.x = frame1.origin.x;
frame.origin.y = frame1.origin.y;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 3.0];
[UIView animateWithDuration:3.0 animations:^{
[oneBtn1 setTransform:CGAffineTransformMakeScale(.4, .4)];
} completion:^(BOOL finished) {
oneBtn1.hidden = YES;
price = [resultText.text intValue];
[resultText setText:[NSString stringWithFormat:#"%i", price+1]];
}];
oneBtn1.frame = frame;
[UIView commitAnimations];
}
Problem: The above text value is 1 but in ViewDidLoad is 0 ,
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"%#", resultText.text); // output is 0 instead of 1;
}
Please anyone tell me how to update the text value in ViewDidLoad function ...

ViewDidLoad calling only once when the object is creating .So you can't update the thing in ViewDidLoad.ViewDidLoad use for initialising the parameters and set the initial settings when an object creating.

This is because every time your view will load it create new object of your textField, thats why you are unable to fetch previous (because its new textField not old one).So you have to save your text some where, for example you can use NSUserDefaults
SetText
NSString *result=[NSString stringWithFormat:#"%i", price+1];
[resultText setText:];
//Also set it to NSUserDefaluts
[[NSUserDefaults standardUserDefaults] setValue:result forKey:#"key"];
[[NSUserDefaults standardUserDefaults] synchronize];
Get Text
- (void)viewDidLoad
{
[resultText setText:[[NSUserDefaults standardUserDefaults] valueForKey:#"key"]];
NSLog(#"%#", resultText.text);
}
EDIT
You can make animation afterButton click, so call this method in button click event
-(void)animateImage
{
if ([resultText.text isEqualToString:#"3"]) {
//make your animation
}
}

You can use a method to do that
- (void)updateLabel {
oneBtn2.userInteractionEnabled = YES;
CGRect frame = oneBtn1.frame;
CGRect frame1 = reffButton.frame;
frame.origin.x = frame1.origin.x;
frame.origin.y = frame1.origin.y;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration: 3.0];
[UIView animateWithDuration:3.0 animations:^{
[oneBtn1 setTransform:CGAffineTransformMakeScale(.4, .4)];
} completion:^(BOOL finished) {
oneBtn1.hidden = YES;
price = [resultText.text intValue];
[resultText setText:[NSString stringWithFormat:#"%i", price+1]];
}];
oneBtn1.frame = frame;
[UIView commitAnimations];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self updateLabel];
NSLog(#"%#", resultText.text); // output is 0 instead of 1;
}

Related

Program multiple animations for single UIImageView with image change

I need to animate a UIImageView inside my application, and cyclically change the UIImage inside it, making it look like an animated photo slideshow.
Right now I'm using an NSTimer to fire every N seconds the UIImage change and the animation itself:
- (void)viewDidLoad {
// NSArray initialization
NSTimer *timer = [NSTimer timerWithTimeInterval:16
target:self
selector:#selector(onTimer)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[timer fire];
[super viewDidLoad];
}
This is the onTimer selector code:
- (void) onTimer {
// cycle through max 9 images
if(imageIndex > 8)
imageIndex = 0;
// set the image
[_imageContainer setImage:[images objectAtIndex:imageIndex]];
// reset width and height of the UIImage frame
CGRect frame = [_imageContainer frame];
frame.size.width -= 170.0f;
frame.size.height -= 100.0f;
[_imageContainer setFrame:frame];
// fade in
[UIView animateKeyframesWithDuration:2.0f delay:0.0f options:0 animations:^{
[_imageContainer setAlpha:1];
} completion:^(BOOL finished) {
// image movement
[UIView animateKeyframesWithDuration:12.0f delay:0.0f options:0 animations:^{
CGRect frame = [_imageContainer frame];
frame.size.width += 170.0f;
frame.size.height += 100.0f;
[_imageContainer setFrame:frame];
} completion:^(BOOL finished) {
// fade out
[UIView animateKeyframesWithDuration:2.0f delay:0.0f options:0 animations:^{
[_imageContainer setAlpha:0];
} completion:nil];
}];
}];
imageIndex++;
}
This seem a very raw but "working" way to achieve what I want but I recognize it might not be the ideal way.
Is there any better method to achieve what I'm looking for?
Updated Answer For Fade Animation
- (void)viewDidLoad
{
[super viewDidLoad];
// self.animationImages is your Image Array
self.animationImages = #[[UIImage imageNamed:#"Image1"], [UIImage imageNamed:#"Image2"]];
// make the first call
[self animateImages];
}
- (void)animateImages
{
static int count = 0;
UIImage *image = [self.animationImages objectAtIndex:(count % [animationImages count])];
[UIView transitionWithView:self.animationImageView
duration:1.0f // animation duration
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
self.animationImageView.image = image; // change to other image
} completion:^(BOOL finished) {
[self animateImages]; // once finished, repeat again
count++; // this is to keep the reference of which image should be loaded next
}];
}

Button's frame is not changing

I have a UIButton at the position x=0.0. Now when I am pressing that button the button is shifting and goes to a position at x=131.0. Now when I am pressing that again it should come back to x=0.0 position. But its not coming. It is staying at the position x=131.0.
This is the code I have written
- (IBAction)showMenuViewButton:(id)sender {
_horizontalConstraintsOfColorViewToMainView.constant = 0.0;
_buttonOfColorViewHoriozontalLeadingConstraints.constant = 131.0;
counter=counter+1;
if (counter%2 !=0) {
[UIView animateWithDuration:0.4
animations:^
{
_menuView.hidden = NO;
_menuView.frame = CGRectMake(0.0, _menuView.frame.origin.y, _menuView.frame.size.width, _menuView.frame.size.height);
_showMenuViewButton.frame = CGRectMake(_showMenuViewButton.frame.origin.x+_menuView.frame.size.width+_showMenuViewButton.frame.size.width,_showMenuViewButton.frame.origin.y, _showMenuViewButton.frame.size.width, _showMenuViewButton.frame.size.width);
}];
}
else{
[UIView animateWithDuration:0.4
animations:^
{
_menuView.hidden = NO;
_menuView.frame = CGRectMake(-102.0, _menuView.frame.origin.y, _menuView.frame.size.width, _menuView.frame.size.height);
_showMenuViewButton.frame = CGRectMake(0.0,_showMenuViewButton.frame.origin.y, _showMenuViewButton.frame.size.width, _showMenuViewButton.frame.size.width);
}];
}
}
Here I have changed button frame for animation not change any contarint
- (IBAction)clickButton:(id)sender {
if (!isChangedPlace) {
isChangedPlace = true;
[UIView animateWithDuration:1.0
animations:^{
btn.frame = CGRectMake(btn.frame.origin.x, btn.frame.origin.y+100, btn.frame.size.width, btn.frame.size[self.height);view layoutIfNeeded];
}];
}
else
{
isChangedPlace = false;
[UIView animateWithDuration:1.0
animations:^{
btn.frame = CGRectMake(btn.frame.origin.x, btn.frame.origin.y-100, btn.frame.size[self.width,view btn.frame.size.height);layoutIfNeeded];
}];
}
}
Here I have change buttons Y constraint for animating it
I have set Y constraint using IBOutlet and change that value as follow.
- (IBAction)clickButton:(id)sender {
if (!isChangedPlace) {
isChangedPlace = true;
buttonYPointConstraint.constant += 50;
}
else
{
isChangedPlace = false;
buttonYPointConstraint.constant -= 50;
}
[UIView animateWithDuration:1.0 animations:^{
[self.view layoutIfNeeded];
}];
}
I hope it will help you!

Fade Button in and Out While being clicked/not clicked

I am trying to get a button to move to random locations inside my view. However, the dot only moves at random when it is pressed. I also want it to fade to a different location if it is not pressed. I used CGRect because I need the dot to stay within the bounds of a specific view.
-(IBAction)randomRed:(id)sender
{
[self redDot];
CGRect senderFrame = [sender frame];
CGRect superBounds = [[sender superview ] bounds];
senderFrame.origin.x = (superBounds.size.width - senderFrame.size.width) * drand48();
senderFrame.origin.y = (superBounds.size.height - senderFrame.size.height) * drand48();
[sender setFrame:senderFrame];
counter = counter - 5;
scoreLabel.text = [NSString stringWithFormat:#"Points %i", counter];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Tapadot Red Dot Buzzer Short" ofType:#"mp3"];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
sound.numberOfLoops = 1;
[sound play];
[self subtractOne];
[self performSelector:#selector(showRedDot) withObject:nil afterDelay:1.0];
}
-(void)startRedDot
{
if (counter ==0)
redDot = [NSTimer scheduledTimerWithTimeInterval:4.0
target:self
selector:#selector(showRedDot)
userInfo:nil
repeats:YES];
}
-(void)showRedDot
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
[redButton setAlpha:1];
[UIView commitAnimations];
[self performSelector:#selector(redDot) withObject:nil afterDelay:1.0];
}
-(void)redDot
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
[redButton setAlpha:0];
[UIView commitAnimations];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self setUpGame];
[self sizing];
}
Currently your random positioning code is only called when the button is pressed.
To get it to move Independent of button presses we should put it in its own method, which can invoke itself after a set duration.
First we need to get a reference to the instance of the button you want to move so we can manipulate it.
Then lets separate the movement code into its own method.
- (void) moveButtonRandomly {
CGSize limits;
CGPoint newPosition;
// Get limits
limits.width = self.view.frame.size.width - button.frame.size.width;
limits.height = self.view.frame.size.height - button.frame.size.height;
// Calculate new Position
newPosition = (CGPoint){ limits.width * drand48(), limits.height * drand48() };
// Set new frame
button.frame = (CGRect){ newPosition, button.frame.size };
}
Change your startRedDot to this, which will construct, and start the timer.
- (void) startRedDot {
redDotTimer = [NSTimer scheduledTimerWithTimeInterval:4.0
target:self
selector:#selector(moveButtonRandomly)
userInfo:nil
repeats:YES];
[redDotTimer fire];
}
The animation is rather simple to add just create a new method which invokes two animations; One which fades out the button with a completion that moves the button, and fires off the next animation to fade it back in.
- (void) moveButtonWithAnimation {
CGFloat fadeDurration;
if ( !button )
return; // only invoke the button if it exists
fadeDurration = 0.4;
//Fade Out
[UIView animateWithDuration: fadeDurration animations:^{
button.alpha = 0.0f;
} completion:^(BOOL finished) {
// Move the button while it is not visible
[self moveButtonRandomly];
// Fade in
[UIView animateWithDuration: fadeDurration animations:^{
button.alpha = 1.0f;
}];
}];
}
Finally Edit the timers selector to be the animation method.
- (void) startRedDot {
redDotTimer = [NSTimer scheduledTimerWithTimeInterval:4.0
target:self
selector:#selector(moveButtonWithAnimation)
userInfo:nil
repeats:YES];
[redDotTimer fire];
}

How to hide an item after fading it out (Objective-C)

I have the following if statement,
if (CGRectIntersectsRect(car.frame, car2.frame) && (upMovement = -1 ) && (car2.hidden == NO)){
[self bounce];
[self carexplode];
if (car2used == NO) {
addedScore = 1;
car2Used = YES;
}
car2.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"car2flames.png"], nil];
[car2 setAnimationRepeatCount:0];
car2.animationDuration = 20;
[car2 startAnimating];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:4];
[iceblock6 setAlpha:0];
[UIView commitAnimations];
car2.hidden = YES;
Essentially, I want it to execute the top part of the method if one car crashes into it, then using UIView animations ^^, I want it to fade out, then be hidden, so that I can set hidden to no again when it reenters the view (after it exits the screen it reloads to the top of the screen). But with this, it just automatically is hidden, without the 4 second fade out animation. How can I fix this? I've tried putting car2.hidden in an if statement, but I don't know what to put in the condition because UIView isn't really bools or integers and all that. Anyone have any advice?
[UIView animateWithDuration:1.0 delay:0.0 options:(UIViewAnimationOptions) animations:^{
//place your animation here
[iceblock6 setAlpha:0];
} completion:^(BOOL finished) {
//called when animation did finish. do what you want
car2.hidden = YES;
}];
Other way:
{
...
if (CGRectIntersectsRect(car.frame, car2.frame) && (upMovement = -1 ) && (car2.hidden == NO)){
[self bounce];
[self carexplode];
if (car2used == NO) {
addedScore = 1;
car2Used = YES;
}
car2.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"car2flames.png"], nil];
[car2 setAnimationRepeatCount:0];
car2.animationDuration = 20;
[car2 startAnimating];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:4.0];
[iceblock6 setAlpha:0];
[UIView commitAnimations];
[self performSelector:#selector(hideCar2) withObject:self afterDelay:4.0];
}
-(void)hideCar2
{
car2.hidden = YES;
}

View is not set back to original position

In my xib i have set one text box ...when user edit in it i am moving that view little up...but when i return back it to its original postion it not come to its original postion it remain little up then original postion.
Here is viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
if ([self respondsToSelector:#selector(edgesForExtendedLayout)])self.edgesForExtendedLayout = UIRectEdgeNone;
search=FALSE;
UIButton *btnOther = [UIButton buttonWithType:UIButtonTypeSystem]; //UIButtonTypeCustom for image button
[btnOther setTitle:#"Save" forState:UIControlStateNormal];
btnOther.titleLabel.font = [UIFont fontWithName:GZFont size:12.0f];
// [btnSave setImage:[UIImage imageNamed:#"save.png"] forState:UIControlStateNormal];
[btnOther addTarget:self action:#selector(btnSaveAction:) forControlEvents:UIControlEventTouchUpInside];
[btnOther setFrame:CGRectMake(0, 0, 55, 29)];
dataArray=[[NSMutableArray alloc]init];
nameSearchArray=[[NSMutableArray alloc]init];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnOther];
txtCharityName.hidden=YES;
txtCharityMail.hidden=YES;
originalCenter=self.view.center;
}
here is textfield delegate methods.:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
if(textField==txtGratuity){
self.view.center=CGPointMake(originalCenter.x, originalCenter.y-30);
}
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
self.view.center=CGPointMake(originalCenter.x, originalCenter.y);
charityId=#"";
NSLog(#"charityID%#",charityId);
}
and here is screenshot.:
as per this equation
frame.origin = center - (bounds.size / 2.0)
center = frame.origin + (bounds.size / 2.0)
you should add 30 points for textfield to get to correct position.
- (void)textFieldDidEndEditing:(UITextField *)textField {
self.view.center=CGPointMake(originalCenter.x, originalCenter.y+30);
charityId=#"";
NSLog(#"charityID%#",charityId);
}
Edit:
try this in your
- (void)textFieldDidBeginEditing:(UITextField *)textField {
[UIView animateWithDuration:0.25
delay:0.0
options: UIViewAnimationOptionCurveEaseInOut
animations:^{
CGRect frame;
// let's move our textField
frame = textField.frame;
frame.origin.y = frame.origin.y-30;
textField.frame=frame;
}
completion:^(BOOL finished){
if(finished) NSLog(#"Finished !!!!!);
}];
}
and move textfield down after edit
- (void)textFieldDidEndEditing:(UITextField *)textField {
[UIView animateWithDuration:0.25
delay:0.0
options: UIViewAnimationOptionCurveEaseInOut
animations:^{
CGRect frame;
// let's move our textField
frame = textField.frame;
frame.origin.y = frame.origin.y+30;
textField.frame=frame;
}
completion:^(BOOL finished){
if(finished) NSLog(#"Finished !!!!!);
}];
}
Set the textfield frames in viewWillAppear instead of viewDidLoad method.

Resources