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

发布于 2024-10-07 07:07:56 字数 108 浏览 0 评论 0原文

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

我怎样才能做到这一点?我需要使用选择器或通知或简单的方法调用吗?

I have written a method and hooked that up with a button so that it gets called when the button is clicked. Now what I want to do is to call that same method when a button on some other view is clicked.

How can I do that? Do I need to use selector or notification or simple method calling?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

很糊涂小朋友 2024-10-14 07:07:56

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

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

或者

只需为按钮方法所在的类创建一个对象,然后以普通方式调用该方法

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];
}

通过设置按钮的 tagValues 来区分发送者

In the selector pass the Target as object of your Class where that method is.

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

Or

Just create a object for the class where your button method is and call that method in ordinary way

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];
}

Differentiate sender by setting tagValues for buttons

浪菊怪哟 2024-10-14 07:07:56

您可以像下面的代码一样使用,将 self 替换为 objectOfTargetClass
并在选择器中需要在该类中点击该方法

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow)name:UIKeyboardWillShowNotification
                                           object:nil];

you can use like the blow code that u replace self by the objectOfTargetClass
and in the selector with the method need to hit in that class

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow)name:UIKeyboardWillShowNotification
                                           object:nil];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文