I am trying to add a tap gesture from a subclassed UIImageView and then control the tap from the View Controller. I am not getting any compiling errors but "addSubview" is not displaying any image. How can make the UIImageView to be displayed?
If I try to control the tap and pan gestures from the subclassed UIImageVIew I have no problems but I would like to control these functions from the View Controller
Relevant code looks like this.
UIImageView subclass
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
//self.userInteractionEnabled = YES;
previewController = [[PreviewController alloc]init];
[previewController self];
[self addSubview:character];
// Tap Initialization code
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:(PreviewController *)self.previewController action:#selector(addCharacter:)];
[self addGestureRecognizer:tap];
self.userInteractionEnabled = YES;
}
return self;
}
View Controller
- (void)addCharacter:(UITapGestureRecognizer *)t
{
NSLog(#"add character");
imageNSArray = [NSMutableArray array];
uiImg = [UIImage imageNamed:#"homer.png"];
CGPoint loc = [t locationInView:self.view];
character = [[UIImageView alloc] initWithImage:uiImg];
character.center = loc;
[imageNSArray addObject:character];
//Locate the imageNSArray on frameImageView area only.
[self.view addSubview:character];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(panCharacter:)];
[self.character addGestureRecognizer:pan];
character.userInteractionEnabled = YES;
}
put a view behind your subclassed imageView. Apply the gestureRecognition to the new View.
You can control your tap gesture from new view. Let me know if i am not clear, or if more info needed.
I think what you want is.. .you want to show a image when user taps on screen.
Do following steps:
1. drag & drop a tap gesture recognizer on default view of your view controller.
2. connect (ctrl +) gestureRecognizer with ViewController.m
Take a look at this code. (Just modified your code)
- (IBAction)onTap:(UITapGestureRecognizer *)sender {
NSLog(#"add character");
UIImage * uiImg = [UIImage imageNamed:#"sel.png"];
CGPoint loc = [sender locationInView:self.view];
UIImageView * character = [[UIImageView alloc] initWithImage:uiImg];
character.center = loc;
[self.view addSubview:character];
}
Let me know if this is not what you want…
Edit
better go for this code… No need to do above steps.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(onTap:)];
[self.view addGestureRecognizer:tap];
self.view.userInteractionEnabled = YES;
}
- (void)onTap:(UITapGestureRecognizer *)sender
{
NSLog(#"add character");
UIImage * uiImg = [UIImage imageNamed:#"sel.png"];
CGPoint loc = [sender locationInView:self.view];
UIImageView * character = [[UIImageView alloc] initWithImage:uiImg];
character.center = loc;
[self.view addSubview:character];
}
Related
Here's my GameViewController.m file:
- (void)viewDidLoad {
[super viewLoad];
.
.
.
_board = [[TwinstonesBoardModel alloc] init];
[_board setToInitialStateMain];
TwinstonesStoneView* twinstonesBoard = [[TwinstonesStoneView alloc]
initWithMainFrame:CGRectMake(12, 160, 301.5, 302.5)
andBoard:_board];
[self.view addSubview:twinstonesBoard];
TwinstonesStonesView *stoneOne = [[TwinstonesStoneView alloc] init];
TwinstonesStonesView *one = (TwinstonesStoneView*)stoneOne.stoneUnoView;
TwinstonesStonesView *stoneTwo = [[TwinstonesStoneView alloc] init];
TwinstonesStonesView *two = (TwinstonesStoneView*)stoneTwo.stoneDueView;
UISwipeGestureRecognizer* swipeLeft = [[UISwipeGestureRecognizer alloc]
initWithTarget:self
action:#selector(swipeLeft:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
swipeLeft.numberOfTouchesRequired = 1;
[one addGestureRecognizer:swipeLeft];
[two addGestureRecognizer:swipeLeft];
Here's the relevant code in my TwinstonesStoneView.m file:
#implementation TwinstonesStoneView
{
NSMutableArray* _array;
NSMutableArray* _emptyArray;
CGRect _frame;
NSUInteger _column;
NSUInteger _row;
TwinstonesBoardModel* _board;
int _i;
}
- (id)initWithMainFrame:(CGRect)frame andBoard:
(TwinstonesBoardModel*)board
{
if (Self = [super initWithFrame:frame])
{
float rowHeight = 49.0;
float columnWidth = 49.0;
float barrierHorizontalRowHeight = 12.5;
float barrierVerticalColumnWidth = 12.5;
for (int row = 0; row < 5; row++)
{
for (int col = 0; col < 5; col++)
{
TwinstonesStonesView* square = [[TwinstonesStoneView alloc]
initWithEmptyFrame:CGRectFrame(//spacial equations, not important)
column:col
row:row
board:board];
BoardCellState state = [board cellStateAtColumn:col andRow:row];
if (state == BoardCellStateStoneOne) {
// _stoneUnoView is a public property
// 'stoneOneCreation' creates a UIImageView of the stone
_stoneUnoView = [UIImageView stoneOneCreation];
[self addSubview:square];
[square addSubview:_stoneUnoView];
[_array insertObject:_stoneUnoView atIndex:0];
} else if (state == BoardCellStateStoneTwo) {
// same idea as above
_stoneDueView = [UIImageView stoneTwoCreation];
[self addSubview:square];
[square addSubview:_stoneDueView];
[_array insertObject:_stoneDueView atIndex:1];
} else {
// based on the 'init' method I write below, I assumed this
// would return an empty square cell
[self addSubview:square];
[_emptyArray insertObject:square atIndex:_i];
_i++;
}
}
}
self.backgroundColor = [UIColor clearColor];
}
return self;
}
- (UIView*)stoneUnoView {
return _stoneUnoView;
}
- (UIView*)stoneDueView {
return _stoneDueView;
}
- (id)initWithEmptyFrame:(CGRect)frame
column:(NSUInteger)column
row:(NSUInteger)row
board:(TwinstonesBoardModel*)board
{
self = [super initWithFrame:frame];
return self;
}
- (void)swipeLeft:(UIGestureRecognizer*)recognizer
{
NSLog(#"Swipe Left");
UIView* view = recognizer.view;
[self move:CGPointMake(-1, 0) withView:view];
}
- (void)move:(CGPoint)direction withView:view {
// whatever code I decide to put for stone movement
}
#end
I apologize for the (probably) unnecessary length, I've just trying to figure this out for a couple days and have had no luck. Here's the bullet points of what I'm trying to do:
1. setInititalStateMain sets the placements of two stones in a 5x5 grid
2. In GameViewController.m, I'm trying to capture the 'stoneUnoView' and
'stoneDueView' properties (set in the TwinstonesStoneView.m file), give them swipe gestures, and interact with them using the methods provided in TwinstonesStoneView.m.
3. Am I generating too many views? The catch is that everything works in terms of what I'm able to see on my IPhone when I run the program. The stones show up on my screen, but when I try to interact with them, not even the 'NSLog' message shows up in the console.
4. The 'stoneOneCreation' method (and ...two) are UIImageView's, but, as you can see, I store them in a UIView pointer.
5. I also used '[one setUserInteractionEnabled:YES]' (and ...two) but that didn't help either.
6. If I add the gesture recognizer to self.view, everything works (the displays of the stones, gameboard, and other graphics appears, and when I interact with ANY part of the screen, I output the directions to the console......just not stone-specific interaction).
Thank you so very much for putting up with all of this, this will really help if someone knows what's wrong. PS: all file #import's are correct, so that isn't a problem.
I am using XCode 7, Objective-C language, and developing for iOS
Anthony
One thing that catches my eye is I don't think you can add the same gesture recognizer to multiple views. I suspect, at best, only the last view is actually receiving it.
try this but i am not sure try this, just create 2 swipe gestures
in GameViewController.m
- (void)viewDidLoad {
[super viewLoad];
//.... other code
//comment below line
// UISwipeGestureRecognizer* swipeLeft = [[UISwipeGestureRecognizer alloc]
//initWithTarget:self //setting self is the problem is the problem
//action:#selector(swipeLeft:)];
UISwipeGestureRecognizer* swipeLeft = [[UISwipeGestureRecognizer alloc]
initWithTarget:stoneOne //set target will be one
action:#selector(swipeLeft:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
swipeLeft.numberOfTouchesRequired = 1;
[one addGestureRecognizer:swipeLeft];
UISwipeGestureRecognizer* swipeLeft_2 = [[UISwipeGestureRecognizer alloc]
initWithTarget:stoneTwo //this will be two
action:#selector(swipeLeft:)];
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
swipeLeft.numberOfTouchesRequired = 1;
[two addGestureRecognizer:swipeLeft_2]; //set the gesture
}
u are setting the gesture to self which means the actions are sent to GameViewController.m but we want actions to be in TwinstonesStoneView.m so change the target to view to TwinstonesStoneView. And also if it is image views u are adding gestures, then enable user interaction for each image views setUserInteractionEnabled:
just try it
Once user double taps on image/screen, it adds an annotation on the screen. When it adds annotation image, I want also open a subview to add annotation detail. However, my subview does not come up.
Here is my code snippet.
#synthesize iViewController;
- (void)viewDidLoad {
[super viewDidLoad];
// adding gesture recognizer
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTapGesture:)];
tapGesture.numberOfTapsRequired = 2;
[self.imvPhoto addGestureRecognizer:tapGesture];
tapGesture.delegate = self;
}
- (void)handleTapGesture:(UITapGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateRecognized) {
// Here is the code for subview adding
iViewController = [[InventoryViewController alloc] init];
[self.view addSubview:iViewController.view];
iViewController.view.frame = CGRectMake(100, 100, 320, 460);
}
}
Based on #rdelmar feedback, here is the solution:
iViewController = (InventoryViewController *)[self.storyboardinstantiateViewControllerWithIdentifier:#"InventoryViewController"];
iViewController.view.frame = CGRectMake(728, 32, 300, 736);
[self.view addSubview:iViewController.view];
I have created image view through code like this -
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib
UIImageView *dot =[[UIImageView alloc] initWithFrame:CGRectMake(50,50,20,20)];
dot.image=[UIImage imageNamed:#"draw.png"];
[self.view addSubview:dot];
}
I want to add User Interaction to this UIImageView and then create a selector or action for this UIImageView when tapped how is this done?
It depends on what kind of action you want achieve. Generally speaking you'd be using UIGestureRecognizer. For instance if you want your image to respond to a tap gesture then you'd have something like the following.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib
dotArray = [NSMutableArray alloc]init];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTapGesture:)];
for(int i = 0; i< 30; i++) {
UIImageView *dot =[[UIImageView alloc] ...
dot.image=[UIImage imageNamed:#"draw.png"];
dot.tag = i; //identify dot image.
[self.view addSubview:dot];
[dotArray addObject:dot];
[dot addGestureRecognizer:tapGesture];
...
}
[tapGesture release];
}
Then the methods to handle tap gesture...
-(void)handleTapGesture:(id)sender {
UITapGestureRecognizer * tapGesture = (UITapGestureRecognizer*)sender;
for(int i = 0; i<[dotArray count]; i++) {
UIImageView * dot = (UIImageView*)[dotArray objectAtIndex:i];
if(dot.tag == [tapGesture view].tag) {
//fade out animation
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5f];
dot.alpha = 0.0f;
[UIView commitAnimations];
}
For this to work, you need to make an array of dots and declare it as instance variable, otherwise the method can't access the dot.
Try like this:-
UIImageView *dot =[[UIImageView alloc] initWithFrame:CGRectMake(50,50,20,20)];
dot.image=[UIImage imageNamed:#"draw.png"];
[self.view addSubview:dot];
1) To implement the number of touch required is 1 refer this:-
UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(scrollViewDoubleTapped:)];
doubleTapRecognizer.numberOfTapsRequired = 2;
doubleTapRecognizer.numberOfTouchesRequired = 1;
[dot addGestureRecognizer:doubleTapRecognizer];
- (void)doubleTapped:(UITapGestureRecognizer*)recognizer
{
}
2) To implement the number of touch required is 2 refer this:-
UITapGestureRecognizer *twoFingerTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(scrollViewTwoFingerTapped:)];
twoFingerTapRecognizer.numberOfTapsRequired = 1;
twoFingerTapRecognizer.numberOfTouchesRequired = 2;
[dot addGestureRecognizer:twoFingerTapRecognizer];
- (void)twoFingerTapped:(UITapGestureRecognizer*)recognizer
{
}
Thank you all of you that helped me I put everyones answers together and got this as my final code.
//
// ViewController.m
// InvaderRush
//
// Created by Ajay Venkat on 13/12/2014.
// Copyright (c) 2014 AJTech. All rights reserved.
//
#import "ViewController.h"
#interface ViewController ()
{
NSArray *dotArray;
}
#end
#implementation ViewController
- (void)viewDidLoad {
UIImageView *dot =[[UIImageView alloc] initWithFrame:CGRectMake(50,50,100,100)];
dot.image=[UIImage imageNamed:#"invader.jpg"];
[self.view addSubview:dot];
dot.tag = 1; //identify dot image.
UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(doubleTapped:)];
doubleTapRecognizer.numberOfTouchesRequired = 1;
[dot addGestureRecognizer:doubleTapRecognizer];
dot.userInteractionEnabled = YES;
NSMutableArray *images =[[NSMutableArray alloc] initWithObjects: dot,nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)doubleTapped:(id)sender {
UIGestureRecognizer *recognizer = (UIGestureRecognizer*)sender;
UIImageView *imageView = (UIImageView *)recognizer.view;
if(imageView.tag==1) {
[imageView setImage:[UIImage imageNamed:#"space_invader.jpg"]];
}
}
-(void)handleTapGesture:(id)sender {
}
#end
I have created a custom annotation and a call out for my map view. I need to navigate to another view when the user clicks on call out view or he clicks to the button that added as sub view to the callout view. But both gesture recognizer and add target is not working for me in this case. The setSelected: method was invoked and the view get hidden when tap occurs in call out view.
#interface VBPunchCardAnnotation : MKAnnotationView{
UIView *calloutView;
}
- (id)initWithAnnotation:(id )annotation reuseIdentifier:(NSString *)reuseIdentifier deal:(id)punchdeal
{
self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
calloutView = [[UIView alloc] init];
calloutView.hidden = YES;
infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
[calloutView addSubview:infoButton];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(annotationTapped:)];
singleTap.numberOfTapsRequired = 1;
singleTap.delegate = self;
[calloutView addGestureRecognizer:singleTap];
[infoButton addTarget:self action:#selector(annotationTapped:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:calloutView];
return self;
}
-(void)setSelected:(BOOL)selected animated:(BOOL)animated
{
// show/hide callout and swap pin image
calloutView.hidden = !selected;
self.image = !selected ? normalPin : selectedPin;
// dispatch an event to alert app a pin has been selected
if(selected) [[NSNotificationCenter defaultCenter] postNotificationName:#"punchCardAnnotation" object:self];
}
-(void)annotationTapped:(id)sender{
[self.delegate punchCardAnnotationClickedForDeal:self.punchDeal];
}
- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event
{
UIView* hitView = [super hitTest:point withEvent:event];
if ([hitView isKindOfClass:[UIButton class]]) {
}
}
Finally I got the answer. It;s here
Followed this tutorial. Really great solution.
https://github.com/nfarina/calloutview
Happy coding!!
In my project I would like to make a hidden image view appear when it is tapped for more than 3 seconds. I know I need to use NSTimer, but I have never created a UIImageView touch event. How can I combine the TapGestureRecognizer with NSTimer to achieve what I want to do? I am completely new to touch events in iOS, and I am just beginning to explore this. So, any help would be appreciated. Thank you!
UPDATE:
I implemented the UILongPressGestureRecognizer as below, but now, the hidden image appears even if I press somewhere outside of the image. How can I make it appear only if pressing the hidden image itself?
- (void)viewDidLoad
{
[super viewDidLoad];
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:#selector(handleLongPress:)];
longPress.numberOfTouchesRequired = 1;
longPress.minimumPressDuration = 3;
[self.view addGestureRecognizer:longPress];
}
-(void)handleLongPress:(UILongPressGestureRecognizer *)gesture
{
if (gesture.state == UIGestureRecognizerStateBegan)
{
BrokenGlass.hidden = NO;
}
}
You don't want a UITapGestureRecognizer and a timer, you want a UILongPressGestureRecognizer.
The image is appearing because you are using the gesture recognizer in the entire view.
[**self.view** addGestureRecognizer:longPress];
The gesture will not trigger on a hidden element.
Here is my solution:
#interface ViewController () <UIGestureRecognizerDelegate>
#property (nonatomic, strong) UIImageView *imageView;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// create the imageView
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
// enable the user interaction in the imageView (otherwise it will not receive events)
_imageView.userInteractionEnabled = YES;
// add as a subview of the main view
[self.view addSubview:_imageView];
// create the gesture recognizer
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(longPressHandler:)];
longPressGesture.delegate = self;
longPressGesture.minimumPressDuration = 3;
// add the gesture to the imageView
[_imageView addGestureRecognizer:longPressGesture];
}
#pragma mark - UIGestureRecognizerDelegate
- (void)longPressHandler:(UILongPressGestureRecognizer *)gestureRecognizer {
// show the image
_imageView.image = [UIImage imageNamed:#"cat.jpeg"];
}