简体   繁体   中英

How do I call a button method from ViewController?

I have a method addClicked that gets called when a button on the navigation bar is clicked. I want to call this later on in the code without having to click the button. What is the syntax for calling this method?

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] 
                                             initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
                                             target:self action:@selector(add_Clicked:)];

The function is calls looks like this:

- (void) add_Clicked:(id)sender {

I tried:

[self add_Clicked:];

[add_Clicked:];

[self add_Clicked: self];

The last works but I'm not sure why. Can someone provide a link to the doc the would explain how this works?

You have to pass something for the sender. That's why the last one works.

Try [self add_Clicked:nil]

最后一个有效是因为您将当前类添加为目标“ target:self”,但是目标是(id),所以发送者理论上可以是任何对象。

Another alternative to the suggestions, depending on what your doing, is to add another method to the class and have the method called form the callback to call it.

- (void) add_Clicked:(id)sender {
  [self goAddSomething];
}


- (void) goAddSomething {
  /* add the code here to handle add. */
}

Then in another part of your code, you could call [self goAddSomething]; and not have to use nil.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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