简体   繁体   English

如何从ViewController调用按钮方法?

[英]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. 我有一个方法addClicked,当单击导航栏上的按钮时会被调用。 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] 尝试[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]; 然后,在代码的另一部分,可以调用[self goAddSomething]; and not have to use nil. 不必使用nil。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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