Krunal
Krunal

Reputation: 6490

Fetch text of UILabel from UIButton

I am new to iPhone,

There are lots of button in my app and on each button i have one UILabel, when user clicks on any button i want to fetch corresponding text of that label from that button.

Here is my code snippet,

- (void) buttonClicked:(UIButton*)sender
{ 
    NSString *Txt=  sender.titleLabel.text;
    NSLog(@"Txt=%@",Txt);
}

but my log shows: Txt=null

Any help will be appreciated.

Upvotes: 0

Views: 177

Answers (2)

Jesse Gumpo
Jesse Gumpo

Reputation: 4787

make sure you are setting the title with:

[button setTitle:@"your title" forState:UIControlStateNormal];

Upvotes: 0

Paresh Navadiya
Paresh Navadiya

Reputation: 38249

I assume u might have subviewed label on button like this:

 UILabel *lblText = [[UILabel alloc]initWithFrame:button.frame];
 lblText.text = @"NameofButton";
 [button addSubview:lblText];
 [lblText release];

Now button click event will be like this:

- (void) buttonClicked:(UIButton*)sender
{ 
  //NSArray *arrSubViews = [sender subviews];
  for (id anObject in [sender subviews]) {
      if([anObject isKindOfClass: [UILabel class]]){
          UIlabel *myLabel = anObject;
          NSString *Txt=  myLabel.text;
          NSLog(@"Txt=%@",Txt);
    }
  }

}

Upvotes: 2

Related Questions