I am dynamically creating UILabels and then saving their tag in an NSMutableArray. I then have a method that detects taps (clicks) on these UILabels. Basically when a UILabel that has been dynamically generated is clicked I want to have it deleted without deleting other labels. However, in future I may want to do more then just delete. But at the moment I feel like I am stuck at a dead end trying to find a way to do this. Any ideas?
Heres my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// set corner radius
coverview.hidden=YES;
labeltextfield.hidden=YES;
textcreate.hidden=YES;
labeltags = [NSMutableArray array];
labeltext = [NSMutableArray array];
}
-(IBAction)removeboard
{
[labeltextfield resignFirstResponder];
}
-(void)showtextcreator {
// Create bg cover
coverview.hidden=NO;
labeltextfield.hidden=NO;
textcreate.hidden=NO;
//Make sure creating screen is always on top
[self.view bringSubviewToFront:coverview];
[self.view bringSubviewToFront:labeltextfield];
[self.view bringSubviewToFront:textcreate];
}
-(void)createtext {
NSInteger obj = [labeltags count] +1 ;
[labeltags addObject:[NSNumber numberWithInteger:0]];
int posx = arc4random() % 300 ;
int posy = arc4random() % 400 ;
int frame = arc4random() % 400 ;
NSString *txt = labeltextfield.text;
// NSString *framename = (#"frame%i",frame);
[labeltext addObject:txt];
[labeltags addObject:[NSNumber numberWithInteger:0]];
CGRect labelframe = CGRectMake( posx, posy, 100, 30);
label = [[UILabel alloc] initWithFrame: labelframe];
[label setText: [NSString stringWithFormat:#"%#", txt]];
[label setTextColor: [UIColor orangeColor]];
label.backgroundColor = [UIColor clearColor];
label.tag=obj;
[self.view addSubview: label];
label.userInteractionEnabled = YES;
UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc]
initWithTarget:self
action:#selector(labelDragged:)];
[label addGestureRecognizer:gesture];
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapAction)];
[label addGestureRecognizer:recognizer];
coverview.hidden=YES;
labeltextfield.hidden=YES;
textcreate.hidden=YES;
}
- (void)labelDragged:(UIPanGestureRecognizer *)gesture
{
label = (UILabel *)gesture.view;
CGPoint translation = [gesture translationInView:label];
// move label
label.center = CGPointMake(label.center.x + translation.x,
label.center.y + translation.y);
// reset translation
[gesture setTranslation:CGPointZero inView:label];
}
- (void)tapAction {
UILabel *labelnew = (UILabel *)[self.view viewWithTag:1];
NSLog(#"Text is %#",labelnew.text);
}
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapAction:)];
[label addGestureRecognizer:recognizer];
- (void)tapAction:(UITapGestureRecognizer *)tapGesture {
UILabel *labelTapped = (UILabel *)tapGesture.view;
//delete it using removeFromSuperView or do whatever you need with tapped label
}
Details:
1.Modify your -(void)createtext method.
2: Add a parameter to the target for UITapGestureRecognizer
3.Receive the sender gesture in - (void)tapAction:
4.Get the tapped UILabel.
Thats it.
Related
I am developing an app where I add images to an NSMutableArray and display them in an image view.
My problem is that I will don't know how to get the index of the selected or tapped image in my app.
FrontsCards=[[NSMutableArray alloc]initWithObjects:#"cloub1.png",#"cloub2.png",#"cloub3.png",#"cloub4.png", nil];
for(int m=0; m< [FrontsCards count];m++)
{
NSString *imageName=[FrontsCards objectAtIndex:m];
NSString *fullImageName=[NSString stringWithFormat:#"%#",imageName];
int padding=25;
CGRect imageViewFrame=CGRectMake(scrollView.frame.size.width*m+padding, scrollView.frame.origin.y, scrollView.frame.size.width-2*padding, scrollView.frame.size.height);
ImgView=[[UIImageView alloc]initWithFrame:imageViewFrame];
[ImgView setImage:[UIImage imageNamed:fullImageName]];
[ImgView setContentMode:UIViewContentModeScaleAspectFill];
[scrollView addSubview:ImgView];
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(doubleTapImgView:)];
doubleTap.numberOfTapsRequired = 2;
doubleTap.delegate = self;
[self.ImgView addGestureRecognizer:doubleTap];
self.ImgView.userInteractionEnabled=YES;
}
CGSize scrollViewSize=CGSizeMake(scrollView.frame.size.width*[FrontsCards count], scrollView.frame.size.height);
[scrollView setContentSize:scrollViewSize];
[self.view addSubview:scrollView];
What should I do in my tap gesture recognizer to get the index of the image?
- (void)doubleTapImgView:(UITapGestureRecognizer *)gesture
{
NSLog(#"double-tap");
}
set a tag to each imageView you using like this :
ImgView=[[UIImageView alloc]initWithFrame:imageViewFrame];
ImgView.tag = m;
and then replace this method:
- (void)doubleTapImgView:(UITapGestureRecognizer *)gesture
{
NSLog(#"double-tap");
NSLog(#"%d", gesture.view.tag);
}
it will print you the index of the image in the imageView
maybe you can use something like this:
first add the name of the image as the accessibilityIdentifier of the the imageview
[imgView setAccessibilityIdentifier:imageName];
then in the tapRecognizer:
-(void)doubleTapImgView:(UITapGestureRecognizer *)gesture{
UIImageView *imgView = (UIImageView *)gesture.view;
int idx = [FrontCards indexOfObject:[imgView accessibilityIdentifier]];
}
UITapGestureRecognizer and UIButton are not working together.
UIButton alone is working fine without UITapGesturerecognizer. It shows in all scrolling image views but after adding UITapGestureReconizer feature it is not showing UIButton when tapped.
BOOL numberofTaps;
#interface ImageScrollViewController : UIViewController <UIGestureRecognizerDelegate>
#property (nonatomic, assign) UITapGestureRecognizer *recognizer;
- (void)handleTap:(UIGestureRecognizer*)sender;
//////////////////////////
- (void)viewDidLoad {
self.view.backgroundColor = [UIColor blackColor];
UIScrollView *imageScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
imageScrollView.pagingEnabled = YES;
NSInteger numberOfViews = 61;
for (int i = 0; i < numberOfViews; i++) {
CGFloat xOrigin = i * self.view.frame.size.width;
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
[myButton addTarget:self action:#selector(dismissView:) forControlEvents:UIControlEventTouchUpInside];
myButton.frame = CGRectMake(xOrigin, 10, 60, 35);
[myButton.layer setMasksToBounds:YES];
[myButton.layer setCornerRadius:10.0f];
myButton.layer.borderWidth = 2;
myButton.layer.borderColor = [[UIColor whiteColor] CGColor];
[myButton setTitle:#"Done" forState:UIControlStateNormal];
myButton.backgroundColor = [UIColor blackColor];
myButton.hidden = YES;
NSString *imageName = [NSString stringWithFormat:#"image%d.png", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(xOrigin, 0, self.view.frame.size.width, self.view.frame.size.height);
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTap:)];
recognizer.numberOfTapsRequired = 1;
[imageView addGestureRecognizer:recognizer];
imageView.userInteractionEnabled = YES;
recognizer.delegate = self;
numberofTaps = 1;
[recognizer release];
[imageScrollView addSubview:imageView];
[imageScrollView addSubview:myButton];
// [imageScrollView addGestureRecognizer:tap];
// [imageView addSubview:tap];
[imageView release];
}
imageScrollView.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews, self.view.frame.size.height);
[self.view addSubview:imageScrollView];
[imageScrollView release];
}
EDIT: Howcome this works but when i only uncomment myButton.hidden= NO then it works but still doesn't shows my button DONE on the imageviews
- (void)handleTap:(UIGestureRecognizer*)sender {
// if(numberofTaps == 1){
CGPoint tapPoint = [sender locationInView:_imageScrollView];
int tapX = (int) tapPoint.x;
int tapY = (int) tapPoint.y;
NSLog(#"TAPPED X:%d Y:%d", tapX, tapY);
//_myButton.hidden = NO;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Hello" message:#"How are you?" delegate:nil cancelButtonTitle:#"I'm awesome." otherButtonTitles:nil];
[alert show];
[alert release];
}
What is the reason that otherwise it is working but not showing Done UIButton.
First you have to find button which you have to show. So for that you will have to setTag: on your UIButton before adding them to scrollView
like this -
myButton.tag = i;
Then add tag to your UIImageView also before adding them to scrollView like this -
imageView.tag = i*100;
Now in handleTap: method you can compare tags and can get the button which you have to show.
-(void)handleTap:(UIGestureRecognizer *)sender
{
//getting all buttons of scrollView
for(UIButton *button in scrollView.subviews)
{
//comparing tags
if(button.tag == sender.view.tag/100)
{
button.hidden = NO;
}
}
}
Do this, remove your if Condition.
when I press on it I can change position freely in View
-(IBAction) add :(id)sender {
CGRect frame = CGRectMake(kLeftMargin, 8.0, kTextFieldWidth, kTextFieldHeight);
UITextField * textfieldToAdd = [[[UITextField alloc] initWithFrame:frame] autorelease];
textfieldToAdd.borderStyle = UITextBorderStyleRoundedRect;
textfieldToAdd.textColor = [UIColor blackColor];
textfieldToAdd.font = [UIFont systemFontOfSize:17.0];
textfieldToAdd.placeholder = #"";
textfieldToAdd.backgroundColor = [UIColor whiteColor];
textfieldToAdd.autocorrectionType = UITextAutocorrectionTypeNo ; // no auto correction support
textfieldToAdd.keyboardType = UIKeyboardTypeDefault; // use the default type input method (entire keyboard)
textfieldToAdd.returnKeyType = UIReturnKeyDone;
textfieldToAdd.clearButtonMode = UITextFieldViewModeWhileEditing; // has a clear 'x' button to the right
textfieldToAdd.tag = kViewTag; // tag this control so we can remove it later for recycled cells
textfieldToAdd.delegate = self; // let us be the delegate so we know when the keyboard's "Done" button is pressed
// Add an accessibility label that describes what the text field is for.
[textfieldToAdd setAccessibilityLabel:NSLocalizedString(#"textfieldToAdd", #"")];
[self.view addSubview:textfieldToAdd];
}
First add the gestureRecognizer to your ViewDidLoad and then create the function
or better look here MoveME example
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(panPiece:)];
[panGesture setMaximumNumberOfTouches:2];
[panGesture setDelegate:self];
[self addGestureRecognizer:panGesture];
- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{
if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
CGPoint translation = [gestureRecognizer translationInView:self.view];
textfieldToAdd.center = CGPointMake([self center].x + translation.x, [self center].y + translation.y);
[gestureRecognizer setTranslation:CGPointZero inView:[self superview]];
}
}
i want dragging this textField
(void)viewDidLoad {
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(add:)] autorelease];
}
-(IBAction) add :(id)sender {
CGRect frame = CGRectMake(kLeftMargin, 8.0, kTextFieldWidth, kTextFieldHeight);
UITextField * textfieldToAdd = [[[UITextField alloc] initWithFrame:frame] autorelease];
textfieldToAdd.borderStyle = UITextBorderStyleRoundedRect;
textfieldToAdd.textColor = [UIColor blackColor];
textfieldToAdd.font = [UIFont systemFontOfSize:17.0];
textfieldToAdd.placeholder = #"";
textfieldToAdd.backgroundColor = [UIColor whiteColor];
textfieldToAdd.autocorrectionType = UITextAutocorrectionTypeNo ; // no auto correction support
textfieldToAdd.keyboardType = UIKeyboardTypeDefault; // use the default type input method (entire keyboard)
textfieldToAdd.returnKeyType = UIReturnKeyDone;
textfieldToAdd.clearButtonMode = UITextFieldViewModeWhileEditing; // has a clear 'x' button to the right
textfieldToAdd.tag = kViewTag; // tag this control so we can remove it later for recycled cells
textfieldToAdd.delegate = self; // let us be the delegate so we know when the keyboard's "Done" button is pressed
// Add an accessibility label that describes what the text field is for.
[textfieldToAdd setAccessibilityLabel:NSLocalizedString(#"textfieldToAdd", #"")];
[self.view addSubview:textfieldToAdd];
}
Hey, guys, I met a problem when trying to removeGestureRecognizer: from a view,
what i want to do is doubleTap one of the imageViews, and remove the tapped imageView's singleTap Gesture, without remove other imageViews singleTap Gesture.
here is how i generate views, gestures and the mechanisms:
.h
UITapGestureRecognizer *singleTap;
.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSInteger i;
for (i = 1; i <= 3; i++)
{
UIImageView *imageView = [[UIImageView alloc] init];
imageView.frame = CGRectMake(110, 70+80*(i-1), 100, 60);
imageView.backgroundColor = [UIColor whiteColor];
imageView.tag = i;
imageView.userInteractionEnabled = YES;
[self.view addSubview:imageView];
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(doubleMethod:)];
doubleTap.numberOfTapsRequired = 2;
singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleMethod:)];
[singleTap requireGestureRecognizerToFail:doubleTap];
[imageView addGestureRecognizer:doubleTap];
[imageView addGestureRecognizer:singleTap];
}
}
- (void)singleMethod: (id)sender
{
NSLog(#"SingleTap");
}
- (void)doubleMethod: (id)sender
{
NSLog(#"%d",[((UITapGestureRecognizer *)sender).view.gestureRecognizers count]);
UIImageView *imageView = nil;
NSArray *tryToFindYou = [self.view subviews];
for (imageView in tryToFindYou)
{
if ([imageView isKindOfClass:[UIImageView class]] && imageView.tag == ((UITapGestureRecognizer *)sender).view.tag)
{
[imageView removeGestureRecognizer:singleTap];
}
}
NSLog(#"%d",[((UITapGestureRecognizer *)sender).view.gestureRecognizers count]);
}
but these lines I wrote can't find exactly the singleTap Gesture attached to the double-tapped imageView.
when NSLog the .gestureRecognizers count, it still 2, what it removed is the last imageView's singleTap Gesture, it became 1, which is correct.
I can't locate the first and second one, any ideas to locate them? thank you for reading :)
You should cycle through gestureRecognizers property of the UIView class, where the gestures are added, something like this:
for (imageView in tryToFindYou)
{
if ([imageView isKindOfClass:[UIImageView class]] && imageView.tag == ((UITapGestureRecognizer *)sender).view.tag)
{
for(UIGestureRecognizer *gesture in [imageView gestureRecognizers])
{
if([gesture isKindOfClass:[UITapGestureRecognizer class]])
{
if (gesture.numberOfTapsRequired == 1)
[imageView removeGestureRecognizer:gesture];
}
}
}
}
I try to make following: Horizontal list of images, that I can select and do something with it. For example flip image around x axis. I know how to rotate image. I created scrollview and load it with images. I added event handler when I tap on image. But I don't know how to do something with tapped image. How to code method to do something with tapped image?
- (void)viewDidLoad {
[super viewDidLoad];
img1 = [UIImage imageNamed:#"imgTest.jpg"];
img2 = [UIImage imageNamed:#"imgTest2.jpg"];
arrayOfImages = [[NSMutableArray alloc] init];
[arrayOfImages addObject:img1];
[arrayOfImages addObject:img2];
[arrayOfImages addObject:img1];
[arrayOfImages addObject:img2];
scrollView = [[UIScrollView alloc] init];
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
scrollView.directionalLockEnabled = YES;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.delegate = self;
scrollView.backgroundColor = [UIColor blueColor];
scrollView.autoresizesSubviews = YES;
scrollView.frame = CGRectMake(0, 0, 320, 128);
[self.view addSubview:scrollView];
UIImage *imageToAdd;
int x = 0;
int y = 0;
for(imageToAdd in arrayOfImages)
{
UIImageView *temp = [[UIImageView alloc] initWithImage:imageToAdd];
temp.frame = CGRectMake(x, y, 128, 128);
temp.userInteractionEnabled = YES;
x += 135;
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(imageTapped:)];
[temp addGestureRecognizer:tap];
[scrollView addSubview:temp];
}
...
- (void)imageTapped:(UIGestureRecognizer *)sender
{
// how to get reference on selected item in scrollview???
}
A gesture recognizer has a view property that returns the view associated with the recognizer. Since you know that it'll be a UIImageView you can simply cast it and use it as in:
UIImageView *iv = (UIImageView *)[sender view];
And your image can then be queried via:
UIImage *image = [iv image];
If you need to know the index in your array, there are two ways: either simply use [arrayOfImages indexOfObject:image];, or you can assign tags (numbers) to views and use them. A tag is not used by Apple, it's only here so we developers can "mark" views in some way. For example:
NSInteger counter = 0;
for(imageToAdd in arrayOfImages)
{
UIImageView *temp = [[UIImageView alloc] initWithImage:imageToAdd];
count.tag = counter++;
...
}
Then, in your imageTapped:, you can query the index via tag:
NSInteger index = [imageView tag];