I have been working on an iOS single view application in Xcode 6 for a couple days, and have hit a roadblock when I try to add touch events. Here is what I am trying to do:
In the storyboard, I have created a UILabel and a UIImageView, I would like to add a tap gesture to the UIImageView so that when I tap the image, the label changes. While I am not very comfortable programming in Objective-C, I do understand that I must first attach the gesture to the UIImageView which can then be handled by my event handler method. Here is what I have attempted:
In the ViewController.h file:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
IBOutlet UIImageView *imageView;
IBOutlet UILabel *myLabel;
}
-(void)handleTap:(id)sender;
@end
In the ViewController.m file:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *pgr = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:@selector(handleTap)];
[imageView addGestureRecognizer:pgr];
[super viewDidLoad];
}
- (void)handleTap:(UITapGestureRecognizer *)tapGestureRecognizer
{
myLabel.text = [NSString stringWithFormat:@"It Worked"];
}
What I expected to happen was that myLabel would change when imageView was tapped, myLabel and imageView being linked to a UILabel and UIImageView respectively. And I do realize I could probably save myself a lot of trouble by just adding a button to the imageView, but I am really trying to make it work with the touch events.
I am new to the language, and this is the first time I have attempted to build something. I have tried to be as detailed as possible when posting this, but if you need more details, I would be happy to provide them. Details, code examples, and explanations of how pieces fit together are greatly appreciated. Thank you.
#import "ViewController.m"
@interface ViewController ()
{
IBOutlet UILabel *myLabel;
IBOutlet UIImageView *myImage;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Tapped:)];
tap.numberOfTapsRequired = 1; //You can change this is double tap ect..
Red.cancelsTouchesInView = YES;
myImage.userInteractionEnabled = YES; //if you want touch on your image you'll need this
[myImage addGestureRecognizer:tap];
}
-(void)Tapped:(UITapGestureRecognizer *)sender
{
myLabel.text = [NSString stringWithFormat:@"It Worked"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
If you're game still doesn't work, you've not connected your label and image to the interface builder. To connect them to the interface builder, you dark the do and connect it to the desired object on the view like in this image, I click on the dot and dragged it to the label.