开发者

Which button called the function?

开发者 https://www.devze.com 2023-02-01 05:00 出处:网络
I have two buttons which call the same function.That functions signature is - (IBAction)eraseTextField {...}

I have two buttons which call the same function. That functions signature is - (IBAction)eraseTextField {...}

I would like to figure out what button called the function. So I would like for the functions signature to be something like

- (IBAction)eraseTextField: (id)sender {...}.

Is there a way for the system to know to send the id of the calling object to a function that it calls? 开发者_高级运维Thanks for the help.


if you use - (IBAction)eraseTextField: (id)sender it will work with interface builder the way you think and sender will be the id of the object that sent the method in IB.

You can choose to write your methods with either - (IBAction)eraseTextField and - (IBAction)eraseTextField:(id)sender both work fine and the sender will be the id of the sender object.


You can assign the tag attribute e.g. //using code

myButton1.tag = 1;
myButton1.tag = 2;

//using builder, go to the attributes inspector and set the tag field

then in (IBAction)eraseTextField:(id)sender

you can see which tag it is, e.g.

switch(sender.tag) {
  case 1: //button 1 clicked
  break;
  case 2: //button 2 clicked
  break;
  default:
  break;
}

It's not a very good approach but it works. For readability, you can assign the integer to a constant. This approach maybe used if the button is not linked in the File Owner. If it's linked, then you can compare the two directly. e.g.

if (myButton1 == sender) {
  //button 1 clicked
}
0

精彩评论

暂无评论...
验证码 换一张
取 消