【问题标题】:How to create Multiple buttons programmatically, get button name whenever press on particular button?如何以编程方式创建多个按钮,在按下特定按钮时获取按钮名称?
【发布时间】:2013-10-07 07:03:58
【问题描述】:

我想使用 MutableArray 计数创建多个按钮。创建按钮后,每当按下特定按钮时,我都想在标签中显示该按钮名称。但是一旦按下按钮,它总是显示 MutableArray 最后一个索引值名称。请帮助解决这个问题。我更新鲜 ti iOS。这是我的代码。

-(void)ViewDidLoad {
    NSMutableArray *Mute_array=[[NSMutableArray alloc]initWithObjects:@"One", @"Two", @"Three", @"Four", @"Five", nil]; 

   for (int k=0; k<[Mute_array count]; k++){
       UIButton *btn_sub_category = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [btn_sub_category addTarget:self action:@selector(clicks:) forControlEvents:UIControlEventTouchDown];
        [btn_sub_category setTitle:[Mute_Sub_Category objectAtIndex:k] forState:UIControlStateNormal];
        btn_sub_category.frame = CGRectMake(278, k*130, 483, 44);
        [self.view addSubview:btn_sub_category];
    }
}

-(void)clicks:(id)sender{
   label.text=[btn_sub_category  currentTitle];       
   //Here a want to send the name of that clicked button current title
}

但是,这里的按钮当前标题始终只显示 MutableArray 最后一个对象“五”。我想要按下按钮的当前标题。

【问题讨论】:

    标签: iphone objective-c uibutton ios6.1


    【解决方案1】:
    -(void)clicks:(id)sender{
        UIButton *theButton = (UIButton*)sender;
        NSString *theButtonTitle = [theButton titleForState:UIControlStateNormal]
        NSLog(@"theButtonTitle :- %@", theButtonTitle);
        label.text=theButtonTitle;       
       //Here a want to send the name of that clicked button current title
    }
    

    试试这个代码。 我使用以下方法获取按钮的标题

    titleForState:

    返回与指定状态关联的标题。 - (NSString *)titleForState:(UIControlState)状态参数

    状态

    The state that uses the title. The possible values are described in UIControlState.
    

    返回值

    指定状态的标题。如果没有设置标题 特定状态,此方法返回与 UIControlStateNormal 状态。

    阅读文档https://developer.apple.com/library/ios/documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html#//apple_ref/occ/instm/UIButton/titleForState

    【讨论】:

      【解决方案2】:

      试试这样:

      -(void) clicks:(id)sender
          {
              if ([sender isKindOfClass:[UIButton class]])
              {
                  UIButton *button = (UIButton*)sender;
                  NSString *title = button.currentTitle;
      
                  // do whatever you want with title
              }
          }
      

      【讨论】:

        【解决方案3】:

        试试喜欢,

        -(void)clicks:(id)sender{
         UIButton *resultebutton= (UIButton*)sender;
           label.text=resultebutton.titleLabel.text; 
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-25
          • 1970-01-01
          相关资源
          最近更新 更多