简体   繁体   English

从UIButton获取UILabel的文本

[英]Fetch text of UILabel from UIButton

I am new to iPhone , 我是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. 我的应用程序中有很多按钮,每个按钮上有一个UILabel ,当用户点击任何按钮时,我想从该按钮获取该标签的相应文本。

Here is my code snippet, 这是我的代码片段,

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

but my log shows: Txt=null 但我的日志显示: Txt=null

Any help will be appreciated. 任何帮助将不胜感激。

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);
    }
  }

}

确保您使用以下方式设置标题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM