My problem is similar to this one with the only exception - my ImageView appears at the same place inside the window with different content in it. Content has unique identifier which I want to use to call content-specific actions.
To quickly recap, the guy is looking for a way to pass a parameter into the selector section of the initWithTarget method.
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTapGesture:itemSKU:)];
How can I pass an attribute to the handleTapGesture method or how do I read the unique value otherwise?
Any thoughts appreciated.
EDIT: The content is being pulled from a database and is different every time. The unique identifier is pretty much like an SSN - doesn't repeat.
You could set the UIImageView tag property with your content identifier, and then read that information form the selector.
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTapGesture:)];
[imageView addGestureRecognizer:tapGesture];
imageView.tag = 0;
And then:
- (void)handleTapGesture:(UITapGestureRecognizer *)sender
{
if( ((UIImageView *) sender.view).tag == 0 ) // Check the identifier
{
// Your code here
}
}
Try extending the UIImageView and add whatever values (as properties) and methods you will need.
#interface UIImageViewWithId: UIImageView
#property int imageId;
#end
Then, if you want to be even MORE awesome you may want to encapsulate your behavior in this "widget"'s implementation. This will keep your ViewController nice and clean, and allow you to use this widget across multiple controllers.
#implementation UIImageViewWithId
#synthesize imageId;
- (void)handleTapGesture:(UIGestureRecognizer *)gesture {
NSLog("Hey look! It's Id #%d", imageId);
}
#end
Then just delegate the tap to the individual UIImageViewWithIds
UIImageViewWithId *imageView = [[UIImageViewWithId ... ]]
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget: imageView action:#selector(handleTapGesture:)];
Related
When tapping a specific button in my app I want an image to show, I did this using an UIImageView. Then I want to hide that image by tapping it, but I don't understand how to do this?
I tried the following code, but it doesn't work.
#implementation ViewController
-(IBAction)pic {
UIImage *img = [UIImage imageNamed:#"test.png"];
[ImageView setImage:img];
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *tapRecognize = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(handleTap:)];
tapRecognizer.delegate = self;
[imageView addGestureRecognizer:tapRecognizer];
}
- (void)handleTap:(UITapGestureRecognizer *)tapGestureRecognizer {
//handle tap
}
Its pretty simple.
Use an UIImageView instead and check that userInteractionEnabled is YES on the UIImageView. Then you can then add a gesture recognizer.
Your .h file should have atleast something like below:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UIGestureRecognizerDelegate>
#property (weak, nonatomic) IBOutlet UIImageView *touchImageView;
#end
Dont forget to connect UIImageView from your storyboard to property declared above.
in your .m file:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.touchImageView.userInteractionEnabled = YES;
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(handleTap:)];
tapRecognizer.delegate = self;
[self.touchImageView addGestureRecognizer:tapRecognizer];
}
- (void)handleTap:(UITapGestureRecognizer *)tapGestureRecognizer {
//handle tap
self.touchImageView.alpha = 0.0f;
}
You could put an image on a button instead. I think using a UIImageView is the right decision though. You need to hook up a gesture to it programmatically. You can do this using something similar to below:
let singleFingerTap = UITapGestureRecognizer(target: self, action: "viewTapped:")
imageView.addGestureRecognizer(singleFingerTap)
You can add a tap gesture recognizer to the UIImageView that contains the image.
var tapGesture = UITapGestureRecognizer(target: <#AnyObject#>, action: <#Selector#>)
In the method you assign as the action, just set myImageView.alpha = 0. This should essentially "hide" your image view. You could also set the height of the image view to 0 if you wanted to hide it in that sense.
An alternative could be to import an open-sourced project, such as the AKImageViewer, to get posts to appear full screen (giving the user a better full view) and allowing them to swipe or cancel to get away from the image (similar to viewing images in the Twitter app.
What I am trying to achieve is this: when I tap an specific UIImageView, the UITapGesture will pass a string into the tap method.
My code follows below: Imagine I have an UIImageView object there already, and when I tap this image, it will make a phone call,
UITapGestureRecognizer *tapFirstGuy = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(makeCallToThisPerson:#"1234567")];
[imageViewOne addGestureRecognizer:tapFirstGuy];
- (void)makeCallToThisPerson:(NSString *)phoneNumber
{
NSString *phoneNum = [NSString stringWithFormat:#"tel:%#", phoneNumber];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNum]];
}
However, I am getting the following compile error: #selector(makeCallToThisPerson:#"1234567");
I cannot figure what is happening. Why can't I pass string to the private method?
One more way you can try writing subclass of UITapGestureRecognizer like that below:-
#interface customTapGestureRecognizer : UITapGestureRecognizer
#property (nonatomic, strong) NSString * phoneNumber;
#end
// customTapGestureRecognizer.m
#implementation customTapGestureRecognizer
#end
// =====================
....
customTapGestureRecognizer *singleTap = [[customTapGestureRecognizer alloc] initWithTarget:self action:#selector(makeCallToThisPerson:)];
singleTap.phoneNumber = #"1234567";
-(void) makeCallToThisPerson:(UITapGestureRecognizer *)tapRecognizer {
customTapGestureRecognizer *tap = (customTapGestureRecognizer *)tapRecognizer;
NSLog(#"phoneNumber : %#", tap.phoneNumber);
}
Note:- The advantages of writing subclass is that you can pass more number of data easily in your UITapGestureRecognizer.
This is wrong, It's not a valid selector.
UITapGestureRecognizer *tapFirstGuy = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(makeCallToThisPerson:#"1234567")];
You need to change to this:
UITapGestureRecognizer *tapFirstGuy = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(makeCallToThisPerson:)];
In your methods the parameter will be the tapGesture, that's it:
- (void)makeCallToThisPerson:(UITapGestureRecognizer *)tapGesture
You can do several things, in order to pas a parameter:
1.- Use de tag of the imageView, the tapGesture knows the view than it´s attached you can use the tag view:
UITapGestureRecognizer *tapFirstGuy = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(makeCallToThisPerson:)];
imageViewOne.tag = 1234567
[imageViewOne addGestureRecognizer:tapFirstGuy];
- (void)makeCallToThisPerson:(UITapGestureRecognizer *)tapGesture
{
NSString *phoneNum = [NSString stringWithFormat:#"tel:%ld",tapGesture.view.tag];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNum]];
}
Other option, subclassing in order to attach a NSString to imageView as a new property.
The action should be just the selector for a method whose signature must be "method that takes a single id parameter and returns void". The id parameter will (typically) be the object sending the message.
The target (the object the action is sent to) can use the sender parameter to extract additional information if needed, but that additional information needs to be asked for. It isn't supplied gratis.
That is, your ImageView subclass might have methods like:
- (void)setPhoneNumber:(NSString *)phoneNumber; // set a phoneNumber property
- (void)prepareToBeTapped
{
UITapGestureRecognizer *tapFirstGuy = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(makeCallToThisPerson:)];
[self addGestureRecognizer:tapFirstGuy];
}
- (void)makeCallToThisPerson:(id)sender
{
NSString *phoneURL = [NSString stringWithFormat:#"tel:%#", phoneNumber];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneURL]];
}
That is, it's not the action nor even the UITapGestureRecognizer that knows the phone number. The target must know (or be able to obtain) the phone number some other way, perhaps carrying it as a settable property.
#OnikIV's suggestion of using the tag would work fine if the value you want to pass is an integer.
If you want to pass a string however it won't work so well.
You could set the tag to a unique value, then in the gesture recoginizer's action method, convert the tag value to an NSNumber and use it as a key to look up a value in a dictionary of phone numbers.
Another other option is to use associative storage to attach strings to your image views. Associative Storage is a technique that lets you attach key/value pairs to any arbitrary NSObject.
I have a sample project called AssociativeStorageDemo on github that shows how to use it.
Simply I want to add a tap gesture for a UIImageView that when the user touches, calls a method that is implemented in another class (not the same class that contains the UIImageView).
Can I do this and if so how can i do it ?
You can do that. But you need the instance of the target class (class in which method is going to execute) as delegate or something in the gesture adding class.
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self.delegate action:#selector(doSomething)];
Here delegate will be the instance of the target class that you have to set before going to that class.
Edit
I will explain a little more. Suppose you have two view controller classes VCA and VCB. you want to call a method in VCA from VCB through a tap gesture.
in VCB.h
#property (nonatomic,assign)VCA *delegate;
in VCB.m
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self.delegate action:#selector(doSomething)];
in VCA.m
You will present/ push VCB
VCB * viewController = [[VCB alloc]init];
viewController.delegate = self;
// push or present viewController
Declare recognizer selector on init
UITapGestureRecognizer *recognizer =
[UITapGestureRecognizer
initWithTarget:objectOfAnotherClass
action:#selector(methodImplementedOnObjectOfAnotherClass:)];
dont forget about defining number of taps (numberOfTapsRequired) and optional gesture recognizer required to fail (requireGestureRecognizerToFail:)
Link to article about selector.
One straightforward approach is calling the method of another class from the selector method of tapGesture ie.
Add UITapGestureRecogniser to the imageview
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:#selector(tapRecognised)];
[imageView addGestureRecognizer:tapGesture];
Dont forget to enable the userInteraction of the UIImageView, because by default for imageview userInteraction is disabled.
you can do this like below.
imageView.userInteractionEnabled = YES;
Then in the selector of tapGestureRecogniser call the method of another class
- (void)tapRecognised
{
[next tappedOnImage];
}
Here next is the object of another class. You can use delegation also to call the method.
Hope this will help you.
here self.desired view is the view in which you want to add gesture and you should add gesture in following way
and "webViewTapped.delegate = self" means you want to call a function of the same class when user tap and you can change it to your desired function by using delegate like self.delegate
UITapGestureRecognizer *viewTapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapAction:)];
webViewTapped.numberOfTapsRequired = 1;
webViewTapped.delegate = self;
[self.desiredView addGestureRecognizer:viewTapped];
- (void)tapAction:(UITapGestureRecognizer *)sender;
{
// do your stuff here
}
I'm using UITapGestureRecognizer because I'm using a UIScrollView that acts as a container for my UILabels. Basically I'm trying to use an action method with arguments so I can e.g. send myLabel.tag value to the action method to know what action to take depending on what UILabel has has been triggered by a tap.
One way of doing it is having as many action methods as UILabels but that isn't very "pretty" codewise. What I would like to achieve is just having one action method with switch statements.
Is this possible or will I have to do it like this (sigh):
UITapGestureRecognizer *myLabel1Tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(myLabel1Tap)];
[myLabel1Tap addGestureRecognizer:myLabel1Tap];
UITapGestureRecognizer *myLabel2Tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(myLabel2Tap)];
[myLabel1Tap addGestureRecognizer:myLabel2Tap];
UITapGestureRecognizer *myLabelNTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(myLabelNTap)];
[myLabel1Tap addGestureRecognizer:myLabelNTap];
- (void)myLabel1Tap {
// Perform action
}
- (void)myLabel2Tap {
// Perform action
}
- (void)myLabelNTap {
// Perform action
}
Add a single gesture recognizer to the view that is the superview of your various labels:
UITapGestureRecognizer *myLabelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(myLabelTapHandler:)];
[myLabelParent addGestureRecognizer:myLabelTap];
Then when you handle the gesture, determine which label was tapped:
-(void)myLabelTapHandler:(UIGestureRecognizer *)gestureRecognizer {
UIView *tappedView = [gestureRecognizer.view hitTest:[gestureRecognizer locationInView:gestureRecognizer.view] withEvent:nil];
// do something with it
}
You can use just one UITapGestureRecognizer and in your gesture handler (your myLaberXTap), which has the syntax:
- (void)handleGesture:(UITapGestureRecognizer*)gestureRecognizer {
...
}
use gesture.view to know which view you are working on.
I know this is really basic stuff but i need to understand whether my understanding of this is correct.
So what i want to do is this. I want an view with a label on which when double tapped flips and loads another view. On the second view i want a UIPickerView and above i have a button saying back. Both views will be of same size as an UIPickerView which is 320px x 216px.
What i am thinking of to do is create two UIViewclasses named labelView and pickerView. I would then create a viewController which on loadView loads labelView then when user double taps the labelView i get an event in labelView class which is sent to my viewController that then can unload loadView and load the pickerView.
Does this sound as the best way to do this ? Is there a simpler way ? I am also unsure how i route the event from the labelView class to the viewControllerclass.
I dont exactly know the most efficient way to do it(as i am also now to this language),but it is for sure that i have solved ur problem. I made a simple program for that.Three classes involved here in my eg are BaseViewController (which will show two views),LabelView and PickerView (according to ur requirement).
In LabelView.h
#protocol LabelViewDelegate
-(void)didTapTwiceLabelView;
#end
#interface LabelView : UIView {
id <LabelViewDelegate> delegate;
}
#property(nonatomic,retain)id <LabelViewDelegate> delegate;
-(void)didTouch;
#end
In LabelView.m
#synthesize delegate;
-(id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self)
{
UILabel* labl = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, frame.size.width-20,20)];
labl.text = #"Some Text";
[self addSubview:labl];
[labl release]; labl = nil;
self.backgroundColor = [UIColor grayColor];
UITapGestureRecognizer* ges = [[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(didTouch)] autorelease];
ges.numberOfTapsRequired = 2;
[self addGestureRecognizer:ges];
}
return self;
}
-(void)didTouch
{
[delegate didTapTwiceLabelView];
}
//=============================================================
In Pickerview.h
#protocol PickerViewDelegate
-(void)didTapBackButton;
#end
#interface PickerView : UIView <UIPickerViewDelegate,UIPickerViewDataSource>{
id <PickerViewDelegate> delegate;
}
#property(nonatomic,retain)id <PickerViewDelegate> delegate;
#end
In Pickerview.m
#implementation PickerView
#synthesize delegate;
-(id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self)
{
UIPickerView* picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 30, 320, 216)];
picker.delegate = self;
picker.dataSource = self;
[self addSubview:picker];
[picker release]; picker = nil;
self.frame = CGRectMake(frame.origin.x, frame.origin.y, 320, 250);
UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setFrame:CGRectMake(10, 1, 50, 27)];
[btn setTitle:#"Back" forState:UIControlStateNormal];
[btn addTarget:self action:#selector(backButton) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn];
}
return self;
}
-(void)backButton
{
[delegate didTapBackButton];
}
//====================================================================
in BaseViewController.h
#import "LabelView.h"
#import "PickerView.h"
#interface VarticalLabel : UIViewController<UITextFieldDelegate,PickerViewDelegate,LabelViewDelegate> {
PickerView* myPickerView;
LabelView* myLabelView;
}
#end
In BaseViewController.m
-(void)viewDidLoad
{
[super viewDidLoad];
myPickerView= [[PickerView alloc] initWithFrame:CGRectMake(0, 50, 320, 250)];
[self.view addSubview:myPickerView];
myPickerView.delegate = self;
myLabelView= [[LabelView alloc] initWithFrame:CGRectMake(0, 50, 320, 250)];
[self.view addSubview:myLabelView];
myLabelView.delegate = self;
myPickerView.hidden = YES;
}
#pragma mark PickerViewDelgate
-(void)didTapBackButton
{
myPickerView.hidden = YES;
myLabelView.hidden = NO;
}
#pragma mark LabelViewDelegate
-(void)didTapTwiceLabelView
{
myPickerView.hidden = NO;
myLabelView.hidden = YES;
}
To get events from a button to the view controller, just hook up the button's event, e.g. touch up inside, to a method in the view controller, using interface builder. (Double tapping is probably more complicated though.)
When you say 'flips', do you mean it actually shows an animation of flipping over a view to show a 'reverse' side? Like in the weather app when you hit the 'i' button? I'm assuming this is what you mean.
Perhaps check TheElements sample example on the iPhone Reference Library, it has an example of flip animation.
Btw, it's not strictly necessary to unload the loadView that is being 'hidden' when you flip -- it saves you having to construct it again when you flip back -- but it may be pertinent if you have memory use concerns, and/or the system warns you about memory being low.
Also, what do you mean by "create a UIView"? Do you mean subclass UIView, or just instantiate a UIVIew and add children view objects to it? The latter is the usual strategy. Don't subclass UIView just because you want to add some things to a UIView.
If you've got one screen of information that gives way to another screen of information, you'd normally make them separate view controllers. So in your case you'd have one view controller with the label and upon receiving the input you want, you'd switch to the view controller composed of the UIPickerView and the button.
Supposing you use Interface Builder, you would probably have a top level XIB (which the normal project templates will have provided) that defines the app delegate and contains a reference to the initial view controller in a separate XIB (also supplied). In the separate XIB you'd probably want to add another view controller by reference (so, put it in, give it the class name but indicate that its description is contained in another file) and in that view controller put in the picker view and the button.
The point of loadView, as separate from the normal class init, is to facilitate naming and linking to an instance in one XIB while having the layout defined in another. View controllers are alloced and inited when something that has a reference to them is alloced and inited. But the view is only loaded when it is going to be presented, and may be unloaded and reloaded while the app is running (though not while it is showing). Generally speaking, views will be loaded when needed and unnecessary views will be unloaded upon a low memory warning. That's all automatic, even if you don't put anything in the XIBs and just create a view programmatically within loadView or as a result of viewDidLoad.
I've made that all sound more complicated than your solution, but it's actually simpler because of the amount you can do in Interface Builder, once you're past the curve of learning it. It may actually be worth jumping straight to the Xcode 4 beta, as it shakes things up quite a lot in this area and sites have reported that a gold master was seeded at one point, so is likely to become the official thing very soon.
With respect to catching the double tap, the easiest thing is a UITapGestureRecognizer (see here). You'd do something like:
// create a tap gesture recogniser, tell it to send events to this instance
// of this class, and to send them via the 'handleGesture:' message, which
// we'll implement below...
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc]
initWithTarget:self action:#selector(handleGesture:)];
// we want double taps
tapGestureRecognizer.numberOfTapsRequired = 2;
// attach the gesture recogniser to the view we want to catch taps on
[labelView addGestureRecognizer:tapGestureRecognizer];
// we have an owning reference to the recogniser but have now given it to
// the label. We don't intend to talk to it again without being prompted,
// so should relinquish ownership
[tapGestureRecognizer release];
/* ... elsewhere ... */
// the method we've nominated to receive gesture events
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer
{
// could check 'gestureRecognizer' against tapGestureRecognizer above if
// we set the same message for multiple recognisers
// just make sure we're getting this because the gesture occurred
if(gestureRecognizer.state == UIGestureRecognizerStateRecognized)
{
// do something to present the other view
}
}
Gesture recognisers are available as of iOS 3.2 (which was for iPad only; so iOS 4.0 on iPhone and iPod Touch).