Iphone 单击按钮时使用选择器调用不同类的方法

Iphone 单击按钮时使用选择器调用不同类的方法,iphone,methods,selector,Iphone,Methods,Selector,我已经编写了一个方法,并将其与一个按钮连接起来,以便在单击按钮时调用它。现在我想做的是,当单击其他视图上的按钮时,调用相同的方法 我该怎么做?是否需要使用选择器、通知或简单方法调用?在选择器中,将目标作为方法所在类的对象传递 [anotherButton addTarget:objectOfAnotherClass action:@selector(yourMethodInAnotherClass) forControlEvents:UIControlEventTouchUpInside];

我已经编写了一个方法,并将其与一个按钮连接起来,以便在单击按钮时调用它。现在我想做的是,当单击其他视图上的按钮时,调用相同的方法


我该怎么做?是否需要使用选择器、通知或简单方法调用?

在选择器中,将目标作为方法所在类的对象传递

[anotherButton addTarget:objectOfAnotherClass action:@selector(yourMethodInAnotherClass) forControlEvents:UIControlEventTouchUpInside];

只需为button方法所在的类创建一个对象,并以普通方式调用该方法

In First Class say firstView
-(IBAction) yourButtonMethod : (id)sender
{
   //Some Code
}

In another class
-(IBAction) yourAnotherButtonMethod : (id)sender
{
 firstView *firstViewObject = [firstView alloc] init];
 [firstViewObject yourButtonMethod:sender];
}

通过设置按钮的标记值来区分发送者

您可以像使用blow代码一样使用objectOfTargetClass替换self 在选择器中,需要在该类中命中该方法

[[NSNotificationCenter defaultCenter]添加观察者:自选择器:@selector(keyboardWillShow)名称:UIKeyboardWillShowNotification
对象:无];

非常感谢您如此迅速的回复,我尝试了两种方法,但都不管用。。。我已经在viewDidLoad()方法中编写了选择器。。。i、 例如,以下代码[anotherButton addTarget:ObjectOtherClass操作:@selector(YourMethodInOtherClass)forControlEvents:UIControlEventTouchUpInside];viewDidLoad()是否是添加选择器的正确位置。我的第二个问题是:你上面提到的两种方法有什么不同。我应该更喜欢哪个??在什么情况下???再次感谢你,再感谢你一次。。您是否收到任何错误或该方法未被调用。第一种方法是最首选的方法。第二种是调用另一个类的方法的正常编程方式。@iPrabu它不起作用,我尝试了第一个代码,它不调用另一个类方法。你知道吗?