代码之家  ›  专栏  ›  技术社区  ›  Organiccat

从IBAction-iPhone获取按钮的文本

  •  30
  • Organiccat  · 技术社区  · 17 年前

    调用iAction时:

    -(IBAction) onClick1: (id) sender;
    

    发送方中传递了什么?因为它是通过IB连接的,我不太确定。我的问题是如何使按钮的文本成为传递的对象(最有可能是NSString),以便在操作实现中调用它。

    -(IBAction) onClick1: (id) sender {
      NSLog(@"User clicked %@", sender);
      // Do something here with the variable 'sender'
    }
    
    7 回复  |  直到 17 年前
        1
  •  60
  •   Matt Ball    17 年前

    这个 sender 应该是启动操作的控件。但是,不应假定其类型,而应将其定义为 id

    - (IBAction)onClick1:(id)sender {
        // Make sure it's a UIButton
        if (![sender isKindOfClass:[UIButton class]])
            return;
    
        NSString *title = [(UIButton *)sender currentTitle];
    }
    
        2
  •  25
  •   Marc W    17 年前

    实际上是:

    -(IBAction) onClick1: (id) sender {
      NSLog(@"User clicked %@", sender);
      // Do something here with the variable 'sender'
    }
    

    sender 不是一个 NSString id . 只是发送事件的控件。因此,如果您的方法在单击按钮时触发 UIButton 将发送已单击的对象。您可以访问所有的标准 方法和属性。

        3
  •  14
  •   GameLoading    9 年前
    -(IBAction)onClick:(id) sender {
         UIButton *btn = (UIButton *)sender;
    
        //now btn is the same object. And to get title directly
        NSLog(@"Clicked button: %@",[[btn titleLabel] text]);
    }
    
        4
  •  10
  •   VSN    14 年前

    只需编写以下代码

    -(IBAction) getButtonTitle:(id)sender
    {
         UIButton *button = (UIButton *)sender; 
         NSString *buttonTitle = button.currentTitle;
         NSLog(@"Button Title %@",buttonTitle);
    
    }
    

    就这样。。。你做到了!!!

        5
  •  2
  •   Marc Charbonneau    17 年前

    发送方应定义为类型id,而不是int或NSString。发送方是调用该方法的实际对象;如果你把它连接到一个按钮,它将是一个UIButton,如果它是一个文本字段,它将是一个UIExtField。您可以使用它从控件获取信息(例如文本字段的当前字符串值),或者如果有多个控件连接到同一操作方法,则将其与IBOutlet实例变量进行比较。

        6
  •  2
  •   Bill the Lizard    15 年前

    您可以使用以下命令获取按钮标签并确定单击了哪个按钮:

    NSLog(@"Clicked button: %@",[[sender titleLabel] text]);
    

    为了回答您的问题,id是来自IB的对象。

        7
  •  1
  •   Hardik Thakkar    8 年前

     NSLog(@"Date::%@",[btn titleForState:UIControlStateNormal]);