Stavros_S
Stavros_S

Reputation: 2235

Getting the text from a label inside of a UIView when UIView is clicked

I have a custom UIView class called TabView. Each TabView has 2 labels in it as well as a few other elements. I add these labels and to the TabView using interface builder. Inside of my view controller that has the TabViews as subviews I attach a touch event to each of the TabViews using the following method

- (void)viewDidLoad
{
    [super viewDidLoad];
    for (UIView *tabView in self.view.subviews) {
        if([tabView isKindOfClass:[DeviceTabView class]]){
            [self addGestureRecogniser:tabView];
        }
    }
}

-(void)addGestureRecogniser:(UIView *)touchView{

    UITapGestureRecognizer *singleTap=[[UITapGestureRecognizer alloc]initWithTarget:self
                                                                             action:@selector(segueToDeviceUpload:)];
    [touchView addGestureRecognizer:singleTap];
}

I need to be able to get the two label values from the clicked UIView so that I can pass it to the following view controller. I know how to pass values around between ViewControllers, just unsure how to grab the labels from the selected TabView. Thanks for any guidance!

Upvotes: 1

Views: 1579

Answers (2)

robert
robert

Reputation: 2842

You get the selected tabView from the UIGestureRecognizer passed to segueToDeviceUpload: via gestureRecognizer.view. I'd suggest to assign some tag to each label so you can get them from the tabView via viewWithTag:

Everything at once:

-(void)segueToDeviceUpload:(UITapGestureRecognizer*)sender{
    UIView *tappedView = sender.view;
    UILabel *label1 = (UILabel*)[tappedView viewWithTag:1];
    UILabel *label2 = (UILabel*)[tappedView viewWithTag:2];
}

Upvotes: 1

username tbd
username tbd

Reputation: 9382

You could get the text by iterating through the view's subviews, similarly to what you're already doing above:

- (void)segueToDeviceUpload:(UIGestureRecognizer *)gestureRecognizer {
    for (UIView *view in gestureRecognizer.view.subviews) {
        if([view isKindOfClass:[UILabel class]]){
            NSLog(@"One piece of text: %@",((UILabel *)view).text);
        }
    }
}

You could use tags to differentiate between each label.

Upvotes: 2

Related Questions