Buttons displaced/distorted when hiding the navigation bar (After Rotation) - ios5

My application has two ViewControllers linked with NavigationController. The First NavigationController has one view with buttons and one view with labels. This view is a circular rotating menu and it represents my home page. The views can rotate with CGAffineTransformMakeRotation - QuartzCore (apparently it's causing the issue) on touchesMoved:.
I wanted to hide the NavigationBar only in this view, so I used setNavigationBarHidden:YES on ViewWillAppear. Then show the bar on ViewWillDisappear.
On the simulator, everything works as expected until i rotate the first ViewController, when i rotate then click on any button (go to the second ViewController) then click on Back (to go back to my first ViewController), everything will be distorted!.
I tried to fix the issue by adding [self.view setBounds:[[UIScreen
mainScreen]bounds]]; *[self.view setFrame:[[UIScreen
mainScreen]bounds]];* in ViewDidLoad method or ViweWillAppear,
the issue remains.
I tried to set NavigationBar alpha to 0 in ViewWillAppear and set
it to 1 on ViewWillDisappear and I tried
self.navigationController.navigationBar.translucent = YES both
options didn't resolve the problem.
I tried to set programmatically views, buttons and labels positions
in ViewWillAppear and it doesn't resolve the problem.
I doubted the animation so I removed it but it hasn't any effect on the problem.
As a beginner I'm unable to resolve this issue, please help!
ViewController.h (first ViewController)
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#interface ViewController : UIViewController
#property (nonatomic, strong) IBOutlet UIView *aView;
#property (nonatomic, strong) IBOutlet UIView *bView;
#property (nonatomic, strong) IBOutlet UIButton *bimg1;
…
#property (strong, nonatomic) IBOutlet UILabel *label1;
…
-(void) rotateTo:(CGFloat)x andY:(CGFloat)y;
#end
ViewController.m
#import "ViewController.h"
#implementation ViewController
#synthesize aView = _aView;
…
#synthesize bimg1 = _bimg1;
…
#synthesize label1 = _label1;
…
static inline double toradians (double degrees) {
return degrees * M_PI/180;
}
-(void)viewDidLoad {
![enter image description here][1][super viewDidLoad];
//Set text font
[_label1 setFont:[UIFont fontWithName:#"Consolas" size:16]];
…
[self.view setBounds:[[UIScreen mainScreen]bounds]];
[self.view setFrame:[[UIScreen mainScreen]bounds]];
}
-(void)viewWillAppear:(BOOL)animated {
self.navigationController.navigationBar.hidden = YES;
printf("Aview x: %f | Aview y: %f \n",self.aView.frame.origin.x, self.aView.frame.origin.y);
printf("Aview width: %f | Aview height: %f \n",self.aView.frame.size.width, self.aView.frame.size.height);
}
-(void)viewWillDisappear:(BOOL)animated {
self.navigationController.navigationBar.hidden = NO;
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint LastTouchPoint = [touch locationInView:self.view];
CGFloat LasTouchx = LastTouchPoint.x;
CGFloat LasTouchy = LastTouchPoint.y;
CGPoint CenterPoint = self.view.center;
CGFloat x = LasTouchx - CenterPoint.x;
[self rotateTo:x andY:y];
}
-(void) rotateTo:(CGFloat)x andY:(CGFloat)y {
CGFloat angle = x/y;
angle = atan(angle);
angle = angle * 360/M_PI;
angle *= 0.0174532925;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:1];
self.aView.transform=CGAffineTransformMakeRotation(-angle);
self.bView.transform=CGAffineTransformMakeRotation(-angle);
self.bimg1.transform=CGAffineTransformMakeRotation(angle);
self.bimg2.transform=CGAffineTransformMakeRotation(angle);
self.bimg3.transform=CGAffineTransformMakeRotation(angle);
self.bimg4.transform=CGAffineTransformMakeRotation(angle);
self.label1.transform=CGAffineTransformMakeRotation(angle);
self.label2.transform=CGAffineTransformMakeRotation(angle);
self.label3.transform=CGAffineTransformMakeRotation(angle);
self.label4.transform=CGAffineTransformMakeRotation(angle);
[UIView commitAnimations];
}
- (void)viewDidUnload
{
[self setBimg1:nil];
…
[self setAView:nil];
[self setBView:nil];
[super viewDidUnload];
}

Yeah, I figured out the problem… The autoresize of the main View was squeezing my subviews when the NavigationController is hidden or not. so i added self.view.autoresizesSubviews = NO; to ViewDidLoad and the problem is fixed.

Related

Image dragging on a UIScrollView

A UIViewController is called when a user touches an image on a UITableViewCell.
It is called using modalViewController.
On this modalViewController is a UIScrollView, with another UIImageView in the middle, that fetches an image using NSDictionary (passed from the UITableViewCell).
Now, what I wanted to achieve was the ability for the user to drag the image vertically only, such that dragging and releasing a little would cause the image to return to the center with animation. If the user drags it to the extremes, the entire UIScrollView is dismissed and the user returns to the UITableView. I used the following code. The issue here is, and as my name suggests, this code is crude. Is there an elegant way of doing this, without the need of so much calculation?
BOOL imageMoved=NO;
- (void) touchesMoved:(NSSet *)touches
withEvent:(UIEvent *)event {
UITouch * touch = [touches anyObject];
CGPoint pos = [touch locationInView: [UIApplication sharedApplication].keyWindow];
CGRect imageRect = _photoImageView.frame;//_photoImageView object of UIImageView
CGFloat imageHeight = imageRect.size.height;//getting height of the image
CGFloat imageTop=240-imageHeight/2;
CGFloat imageBottom=imageTop+imageHeight;//setting boundaries for getting coordinates of touch.
// Touches that originate above imageTop and below imageBottom are ignored(until touch reaches UIImageView)
if (pos.y>50&&pos.y<430&&pos.y>=imageTop&&pos.y<=imageBottom){//extremes are defined as top and bottom 50 pixels.
imagedMoved=YES;//BOOL variable to hold if the image was dragged or not
NSLog(#"%f", pos.y);
[UIView setAnimationDelay:0];
[UIView animateWithDuration:0.4
animations:^{_photoImageView.frame=CGRectMake(0,pos.y-imageHeight/2,320,200);}
completion:^(BOOL finished){ }];
}
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch * touch = [touches anyObject];
CGPoint pos = [touch locationInView: [UIApplication sharedApplication].keyWindow];
if (pos.y>50&&pos.y<430){//if touch has NOT ended in the extreme 50 pixels vertically
[UIView setAnimationDelay:0];//restoring UIImageView to original center with animation
[UIView animateWithDuration:0.4
animations:^{_photoImageView.frame=CGRectMake(0,140,320,200);}
completion:^(BOOL finished){ }];
imagedMoved=NO;//prepare BOOL value for next touch event
}
else if(pos.y<50||pos.y>430)
if(imagedMoved)
[self.photoBrowser exit] ;//exit function(imported from UIScrollViewController) dismisses
//modalView using [self dismissViewControllerAnimated:YES completion:nil];
}
All code here is a modification onto a customized copy of UITapView in MWPhotoBrowser.
Yo, here is a much easier way to do this, more or less an example of what Alessandro stated. I'm not finding the top of the screen but I'm giving the illusion of it.
BCViewController.h
#import <UIKit/UIKit.h>
#interface BCViewController : UIViewController <UIScrollViewDelegate>
#property (weak, nonatomic) IBOutlet UIScrollView *svScroller;
#property (weak, nonatomic) IBOutlet UIImageView *ivFish;
#end
#import "BCViewController.h"
#interface BCViewController (){
UIPanGestureRecognizer *_panGestureRecognizer;
CGPoint _fishOrigin;
}
#end
#implementation BCViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.svScroller.delegate = self;
[self.svScroller setContentSize:self.view.frame.size];
self.svScroller.translatesAutoresizingMaskIntoConstraints = NO;
self.ivFish.userInteractionEnabled = YES;
_panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(handlePanFrom:)];
[self.ivFish addGestureRecognizer:_panGestureRecognizer];
_fishOrigin = self.ivFish.center;
NSLog(#"center %f", self.ivFish.center.x);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)handlePanFrom:(UIPanGestureRecognizer *)recognizer{
// if you want it but not used
CGPoint translation = [recognizer translationInView:recognizer.view];
// if you want it but not used
CGPoint velocity = [recognizer velocityInView:recognizer.view];
CGPoint tempPoint;
if (recognizer.state == UIGestureRecognizerStateBegan) {
} else if (recognizer.state == UIGestureRecognizerStateChanged) {
tempPoint = [recognizer locationInView:self.view];
self.ivFish.center = CGPointMake(175.5, tempPoint.y);
} else if (recognizer.state == UIGestureRecognizerStateEnded) {
CGPoint tempPoint;
tempPoint = [recognizer locationInView:self.view];
if (tempPoint.y < 132) {
[UIView animateWithDuration:.3 delay:0
options:UIViewAnimationOptionCurveEaseOut
animations:^ {
[self.navigationController popViewControllerAnimated:TRUE];
}
completion:NULL];
} else {
[UIView animateWithDuration:.3 delay:0
options:UIViewAnimationOptionCurveEaseOut
animations:^ {
self.ivFish.center = _fishOrigin;
}
completion:NULL];
}
}
}

How to make a view appear through animation when a button is clicked?

I am new to the coding. I am making an application where i need to make a view appear when a button is clicked and the view should appear as if it has come from the button itself. And on clicking the button again the view should go back to button (animated).
I have animations like flip, curl but I don't know how to do this.
Here is a simple example. Set showView: as the button's action.
- (IBAction)showView:(UIButton *)sender {
// Create a view with the size and position of the tapped button
UIView *view = [[UIView alloc] initWithFrame:sender.frame];
// Set a color on the view
view.backgroundColor = [UIColor redColor];
// Add the new view to the main view. The new view will be displayed over any other views
[self.view addSubview:view];
// Animate the change of the new view's frame. We use the bounds of the main view.
[UIView animateWithDuration:3.6 animations:^{
view.frame = self.view.bounds;
}];
}
Complete solution:
First create properties for the view and the button. How you initialize these is up to you.
#property (strong, nonatomic) UIButton *button;
#property (strong, nonatomic) UIView *aView;
...
#synthesize button = _button;
#synthesize aView = _aView;
Then create a method that animates a view between two frames and will remove the view from its superview at the end of the animation if asked to.
- (void)animateView:(UIView *)view
fromRect:(CGRect)from
toRect:(CGRect)to
inParentView:(UIView *)parent
removeWhenDone:(BOOL)remove
{
if (!remove) {
[parent addSubview:view];
}
view.frame = from;
[UIView animateWithDuration:3.6 animations:^{
view.frame = to;
} completion:^(BOOL finished) {
if (remove) {
[view removeFromSuperview];
}
}];
}
Then create a boolean property that indicates if the view is shown, and implement a custom setter for the property.
#property (assign, nonatomic) BOOL viewShown;
...
#synthesize viewShown = _viewShown;
- (void)setViewShown:(BOOL)viewShown
{
_viewShown = viewShown;
if (_viewShown) {
// Insert your own toRect
[self animateView:self.aView fromRect:self.button.frame toRect:CGRectMake(0, 0, 100, 100) inParentView:self.view removeWhenDone:NO];
} else {
[self animateView:self.aView fromRect:self.aView.frame toRect:self.button.frame inParentView:self.view removeWhenDone:YES];
}
}
Finally, in the button's action you flip the viewShown property.
- (IBAction)showView:(UIButton *)sender {
self.viewShown = !self.viewShown;
}
//Here animationButton is the name of the button
// Here aView is a view
aView.view.center=animationButton.center;
Now,scale the view to a small scale as shown so that when you make it bib,it gets shown as if it is coming from the button itself.
CGAffineTransform trans = CGAffineTransformScale(aView.view.transform, 0.01, 0.01);
aView.view.transform = trans; // do it instantly, no animation
[self.view addSubview:aView.view];
// now return the view to normal dimension, animating this transformation
//Now with the help of animation ,scale the view to some large extent by animation
[UIView animateWithDuration:2.0 delay:0.0 options:UIViewAnimationCurveEaseInOut
animations:^{
aView.view.transform = CGAffineTransformScale(aView.view.transform, 70.0, 70.0);
}
completion:nil];

How to scroll view up when keyboard appears?

I know that this question has been asked over and over again, but nothing seems to be working for me. Most of the solutions around are pretty out of date, and the rest are incredibly huge blocks of code that are ten times larger then the actual projects coding. I have a few UITextFields lined up vertically, but when the keyboard launches to edit one, it covers up the text field. I was wondering if there is a simple beginner way to scroll the view up, and then back down when the editing starts and ends?
Thank you.
I have made solutions that work with scroll and non-scroll views using keyboard notification and a detection of the current first responder, but sometimes I use this trivial solution instead: The simple way is to detect the opening keyboard via the text field delegate's textViewDidBeginEditing: method and to move the entire view up. The easiest way to do this is with something along the lines of changing self.view.bounds.origin.y to -100 (or whatever). Use the corresponding textViewShouldEndEditing: method to set it to the opposite, which is 100 in this case. Changing bounds is a relative procedure. After changing it the frame is moved but the bounds origin is still zero.
Since I found it, I use TPKeyboardAvoiding - https://github.com/michaeltyson/TPKeyboardAvoiding.
It is working great, and is very easy to setup:
Add a UIScrollView into your view controller's xib
Set the scroll view's class to TPKeyboardAvoidingScrollView (still in the xib, via the identity inspector)
Place all your controls within that scroll view
You can also create it programmatically, if you want.
There is a class for the same need inside a UITableViewController ; it is only needed in case you support a version of iOS below 4.3.
#BenLu and other users who are facing problem of the function are never getting called is because of following reason:
As the delegate inbuild function bydefaults return void instead of BOOL this is how it should be as follows:
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.35f];
CGRect frame = self.view.frame;
frame.origin.y = -100;
[self.view setFrame:frame];
[UIView commitAnimations];
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.35f];
CGRect frame = self.view.frame;
frame.origin.y = 100;
[self.view setFrame:frame];
[UIView commitAnimations];
}
I spent sometime on this problem and gathered pieces code to create one final solution. My problem was related to UITableView scrolling and keyboard open/close.
You need two partial methods in your cell class:
void EditingBegin(UITextField sender)
{
// Height of tallest cell, you can ignore this!
float tableMargin = 70.0f;
float tableHeight = _tableView.Frame.Size.Height;
float keyBoardHeight = KeyboardHeight();
NSIndexPath[] paths = this._tableView.IndexPathsForVisibleRows;
RectangleF rectLast = this._tableView.RectForSection(paths[paths.Length - 1].Section);
RectangleF rectFirst = this._tableView.RectForSection(paths[0].Section);
float lastCellY = rectLast.Y - rectFirst.Y;
if (lastCellY > tableHeight - keyBoardHeight)
{
float diff = lastCellY - (tableHeight - tableMargin - keyBoardHeight);
this._tableView.ContentInset = new UIEdgeInsets(0.0f, 0.0f, diff, 0.0f);
}
float cellPosition = this._tableView.RectForSection(this._section).Y;
if (cellPosition > tableHeight - keyBoardHeight)
{
if (this._tableView.ContentInset.Bottom == 0.0f)
{
float diff = cellPosition - (tableHeight - tableMargin - keyBoardHeight);
this._tableView.ContentInset = new UIEdgeInsets(0.0f, 0.0f, diff, 0.0f);
}
else
{
this._tableView.ScrollToRow(NSIndexPath.FromItemSection(0, this._section), UITableViewScrollPosition.Middle, true);
}
}
}
partial void EditingEnd(UITextField sender)
{
UIView.BeginAnimations(null);
UIView.SetAnimationDuration(0.3f);
this._tableView.ContentInset = new UIEdgeInsets(0.0f, 0.0f, 0.0f, 0.0f);
UIView.CommitAnimations();
}
and then in your view controller class:
public override void WillAnimateRotation(UIInterfaceOrientation toInterfaceOrientation, double duration)
{
base.WillAnimateRotation(toInterfaceOrientation, duration);
float bottom = this.TableView.ContentInset.Bottom;
if (bottom > 0.0f)
{
if (toInterfaceOrientation == UIInterfaceOrientation.Portrait || toInterfaceOrientation == UIInterfaceOrientation.PortraitUpsideDown)
{
bottom = bottom * UIScreen.MainScreen.Bounds.Width / UIScreen.MainScreen.Bounds.Height;
}
else
{
bottom = bottom * UIScreen.MainScreen.Bounds.Height / UIScreen.MainScreen.Bounds.Width;
}
UIEdgeInsets insets = this.TableView.ContentInset;
this.TableView.ContentInset = new UIEdgeInsets(0.0f, 0.0f, bottom, 0.0f);
}
}
If you have a UITableView or a UIScrollView it's better to change values for contentOffset instead of making changes to the frame.
Working on Peter's Answer, adding this method to your class works nicely:
- (void)textViewDidBeginEditing:(UITextField *)textField {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.35f];
CGPoint offset = self.tableView.contentOffset;
offset.y += 200; // You can change this, but 200 doesn't create any problems
[self.tableView setContentOffset:offset];
[UIView commitAnimations];
}
That's it, no need to add the textViewDidEndEditing method.
I shouldn't need to say this, but for this to work your UITextField or UITextView must be a delegate of your controller.
Starting with Peter's answer, I developed the following approach in Swift 3.0 under iOS 10.1. I'm doing this for a textView, so I have implemented the UITextViewDelegate functions textViewDidBeginEditing and textViewDidEndEditing where I adjust the view's bounds. As you can see, I set the origin Y value to a small positive number to scroll up and then back to 0 to return to the original position.
Here is the relevant code from my ViewController. You don't need to animate, but it adds a nice touch.
func textViewDidBeginEditing(_ textView: UITextView)
{
if UIScreen.main.bounds.height < 568 {
UIView.animate(withDuration: 0.75, animations: {
self.view.bounds.origin.y = 60
})
}
}
func textViewDidEndEditing(_ textView: UITextView)
{
if UIScreen.main.bounds.height < 568 {
UIView.animate(withDuration: 0.75, animations: {
self.view.bounds.origin.y = 0
})
}
}
i have a scrollview and 3 text fields in this. I have a simple code from my own application :
.h file is :
#import <UIKit/UIKit.h>
#interface AddContactViewController : UIViewController<UITextFieldDelegate, UIScrollViewDelegate>
#property (nonatomic, retain) NSDictionary *dict_contactDetail;
#property (nonatomic, retain) IBOutlet UILabel *lbl_name;
#property (nonatomic, retain) IBOutlet UITextField *txtField_tel;
#property (nonatomic, retain) IBOutlet UITextField *txtField_address;
#property (nonatomic, retain) IBOutlet UITextField *txtField_email;
#property (nonatomic, retain) IBOutlet UIScrollView *scrollView;
#end
.m file :
#import "AddContactViewController.h"
#interface AddContactViewController ()
#end
#implementation AddContactViewController
#synthesize dict_contactDetail;
#synthesize lbl_name, txtField_tel, txtField_email, txtField_address, scrollView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// NSLog(#"dict_contactDetail : %#", dict_contactDetail);
UIBarButtonItem * rightButton = [[UIBarButtonItem alloc] initWithTitle:#"Add" style:UIBarButtonSystemItemDone target:self action:#selector(addEmergencyContact:)];
self.navigationItem.rightBarButtonItem = rightButton;
lbl_name.text = [NSString stringWithFormat:#"%# %#", [dict_contactDetail valueForKey:#"fname"], [dict_contactDetail valueForKey:#"lname"]];
txtField_tel.returnKeyType = UIReturnKeyDone;
txtField_email.returnKeyType = UIReturnKeyDone;
txtField_address.returnKeyType = UIReturnKeyDone;
}
-(void)addEmergencyContact:(id)sender
{
scrollView.frame = CGRectMake(0, 0, 320, 460);
}
#pragma mark - text field delegates
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
if([textField isEqual:txtField_tel])
{
[scrollView setContentOffset:CGPointMake(0, 70)];
scrollView.frame = CGRectMake(0, 0, 320, 210);
}
if([textField isEqual:txtField_address])
{
[scrollView setContentOffset:CGPointMake(0, 140)];
scrollView.frame = CGRectMake(0, 0, 320, 210);
}
if([textField isEqual:txtField_email])
{
[scrollView setContentOffset:CGPointMake(0, 210)];
scrollView.frame = CGRectMake(0, 0, 320, 210);
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
scrollView.frame = CGRectMake(0, 0, 320, 460);
[textField resignFirstResponder];
return YES;
}
#end

How to stop a tap from counting when the timer is paused in xcode

I am designing an iphone app that basically lets the user tap a ball on screen and the app counts how many times the user taps the ball, the problem is, the app counts the taps from before the start button is tapped. How would I stop the taps from counting toward your score before the start button is tapped?
Here is my code:
.h:
#interface FlipsideViewController : UIViewController {
IBOutlet UIImageView *Ball1;
NSTimer *mainTimer1;
IBOutlet UIButton *startButton1;
IBOutlet UILabel *currentNumber1;
IBOutlet UIButton *pause1;
UIAlertView *alertStart1;
}
#property (nonatomic, assign) id <FlipsideViewControllerDelegate> delegate;
#property (nonatomic, retain) UIImageView *Ball1;
#property (nonatomic, retain) NSTimer *mainTimer1;
#property (nonatomic, retain) UIButton *startButton1;
- (IBAction)done:(id)sender;
- (IBAction)startMove;
- (void)moveBall;
- (BOOL)Intersecting:(CGPoint)loctouch:(UIImageView *)enemyimg;
- (IBAction)pause1:(id)sender;
- (void)alertStart1;
#end
.m:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:self.view];
// if user touched ball, stop timer
if ([self Intersecting:location :Ball1]) {
[mainTimer1 invalidate];
mainTimer1 = nil;
startButton1.hidden = NO;
number++;
[currentNumber1 setText:[NSString stringWithFormat:#"%d", number]];
}
}
-(BOOL)Intersecting:(CGPoint)loctouch:(UIImageView *)enemyimg {
CGFloat x1 = loctouch.x;
CGFloat y1 = loctouch.y;
CGFloat x2 = enemyimg.frame.origin.x;
CGFloat y2 = enemyimg.frame.origin.y;
CGFloat w2 = enemyimg.frame.size.width;
CGFloat h2 = enemyimg.frame.size.height;
if ((x1>x2)&&(x1<x2+w2)&&(y1>y2)&&(y1<y2+h2))
return YES;
else
return NO;
}
-(void)moveBall {
CGFloat xdist = fabs(Destination.x-Ball1.center.x);
CGFloat ydist = fabs(Destination.y-Ball1.center.y);
if ((xdist<5)&&(ydist<5)) {
Destination = CGPointMake(arc4random() % 320, arc4random() % 480);
xamt = ((Destination.x - Ball1.center.x) / speed);
yamt = ((Destination.y - Ball1.center.y) / speed);
} else {
Ball1.center = CGPointMake(Ball1.center.x+xamt, Ball1.center.y+yamt);
}
}
-(IBAction)startMove {
startButton1.hidden = YES;
Destination = CGPointMake(arc4random() % 320, arc4random() % 480);
xamt = ((Destination.x - Ball1.center.x) / speed);
yamt = ((Destination.y - Ball1.center.y) / speed);
mainTimer1 = [NSTimer scheduledTimerWithTimeInterval:(0.02) target:self selector:#selector(moveBall) userInfo:nil repeats: YES];
}
In the method
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
put a check to see if the game has begun, e.g.
if (startButton1.hidden) {
// game has begun, add points
} else {
// game hasn't yet begun, don't add points
}
If your application is gonna be for iOS 3.2+, use UITapGestureRecognizer instead of touchesBegan:withEvent: and then when the user press the start button add the recognizer to the imageView. Also remember to set the userInteractionEnabled to YES of the UIImageView in order to use UIGestureRecognizer's on them.

Objective-c animation block doesn't seem to fire

I have a method in my UIView subclass "Card" to dismiss an instance by fading its alpha from 1 to 0. I do a similar thing when I add the card to the superview and it fades in fine. But when I call fadeAway, it just disappears immediately. The presentation code is in my controller class. Here is my Card.h and Card.m
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#class Card;
#interface Card : UIView {
int upperOperand;
int lowerOperand;
NSString* theOperator;
int theResult;
}
#property(nonatomic) int upperOperand;
#property(nonatomic) int lowerOperand;
#property(nonatomic, retain) NSString* theOperator;
#property(nonatomic) int theResult;
- (void)fadeAway;
#end
#import "Card.h"
#implementation Card
#synthesize upperOperand;
#synthesize lowerOperand;
#synthesize theOperator;
#synthesize theResult;
- (void)fadeAway {
self.alpha = 1.0f;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:2.0f];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
self.alpha = 0.0f;
[UIView commitAnimations];
[self removeFromSuperview];
}
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
// Initialization code
self.backgroundColor = [UIColor redColor];
self.layer.cornerRadius = 15;
self.alpha = 1.0;
self.layer.borderColor = [[UIColor blueColor] CGColor];
self.layer.borderWidth = 4;
}
return self;
- (void)dealloc {
[super dealloc];
}
#end
Since you're removing self from its superview immediately, I don't think it ever has a chance to perform the animation.
You might want to look into setAnimationDidStopSelector:. There's a discussion on this here: Animation End Callback for CALayer?
Another idea is to delay the removal of the subview. For example,
[self performSelector:#selector(removeFromSuperview)
withObject:nil
afterDelay:2.0f];