Get text of button from IBAction

When an IBAction is called:

-(IBAction) onClick1: (id) sender;

What is passed in the sender? Since it's hooked up through the IB, I'm not really sure. My question is how to get the text of the button to be the passed object (NSString most likely) so that I could call it inside the action implementation.

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

It's actually:

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

sender is not a NSString , it's of type id . It's just the control that sent the event. So if your method is trigged on a button click, the UIButton object that was clicked will be sent. You can access all of the standard UIButton methods and properties programmatically.


The sender should be the control which initiated the action. However, you should not assume its type and should instead leave it defined as an id . Instead, check for the object's class in the actual method as follows:

- (IBAction)onClick1:(id)sender {
    // Make sure it's a UIButton
    if (![sender isKindOfClass:[UIButton class]])
        return;

    NSString *title = [(UIButton *)sender currentTitle];
}

-(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]);
}
链接地址: http://www.djcxy.com/p/85236.html

上一篇: 如何从JSON获取字符串对象而不是Unicode?

下一篇: 从IBAction获取按钮的文本