HurkNburkS
HurkNburkS

Reputation: 5510

Access selected UILabel values

I have created a UILabel and hooked it up to a method using a selector, I would like to know how to access the labels information and text in the method that has been connected with the selector.

This is what my code looks like

cutField.userInteractionEnabled = YES;
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelSelected)];
        [cutField addGestureRecognizer:tapGesture];

and then this is my method

- (void) labelSelected {
    NSLog(@"Selected how do i get selected labels text here?");
}

Upvotes: 0

Views: 74

Answers (1)

Mundi
Mundi

Reputation: 80265

I assume you have many labels, otherwise your controller should just keep a reference to your label (e.g. cutField of type UILabel) and use that.

@interface Controller () {
  UILabel *cutField;
}
@end

The solution to generalize this has two steps. First, change your method signature to one that includes the tap gesture. All you have to do in the init call is to add a colon (:) to the selector.

UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] 
    initWithTarget:self action:@selector(labelSelected:)];

The method can now use the gesture recognizer's view property to get to the label to which it is attached.

-(void) labelSelected:(UITapGestureRecognizer*)recognizer {
    UILabel *label = (UILabel*) recognizer.view;
    NSString *labelText = label.text;
}

Upvotes: 2

Related Questions