UIButton 在代码中设置触摸处理程序

发布于 2024-12-12 09:50:05 字数 437 浏览 0 评论 0原文

我想要实现触摸一个UIButton并让代码在与所有者不同的不同类中运行。

我意识到我可以对按钮的所有者ClassA)执行touchUpInside,然后调用ClassB内部的方法我想打电话,但是有什么办法可以加快吗?

想法:

  • ClassB 成为 ClassA->UIButton

    的委托,
  • 在编程中设置touchUpInside调用,以使用ClassB内部的函数

我不知道如何实现这些想法:(输入是值得赞赏的!

I want to accomplish touching a UIButton and having code run in a different class than the owner.

I realize I can do a touchUpInside to the button's owner (ClassA) and then call the method inside ClassB that I want called, but is there any way to expedite this?

ideas:

  • have ClassB be the delegate for the ClassA->UIButton

  • set the touchUpInside call in programming to used the function inside ClassB

I'm not sure how to accomplish either of these ideas :( Input is mas appreciated!

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

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

发布评论

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

评论(1

川水往事 2024-12-19 09:50:05

一种选择是使用设置按钮

[myButton addTarget:yourOtherClass action:@selector(mySelector:) forControlEvents:UIControlEventTouchUpInside];

,但这有点危险,因为 target 不会保留,因此您可以将消息发送到已释放的对象。

您可以改为设置一个协议

MyController.h

@protocol MyControllerDelegate
- (void)myController:(MyController *)controller buttonTapped:(UIButton *)button;
@end

@interface MyController : UIViewController

@property (nonatomic, assign) id <MyControllerDelegate> delegate;

- (IBAction)buttonTapped:(UIButton *)button;

@end

然后在您的实现中

MyController.m

- (IBAction)buttonTapped:(UIButton *)button
{
    if ([self.delegate respondsToSelector:@selector(myController:buttonTapped:)]) {
      [self.delegate myController:self buttonTapped:button];
    }
}

由于协议中定义的方法不是可选的,我可以改为检查 (self.delegate) 以确保它被设置而不是 <代码>respondsToSelector。

One option is to set the button up using

[myButton addTarget:yourOtherClass action:@selector(mySelector:) forControlEvents:UIControlEventTouchUpInside];

but this is a bit dangerous because target is not retained so you could send the message to a deallocated object.

You could instead set up a protocol

MyController.h

@protocol MyControllerDelegate
- (void)myController:(MyController *)controller buttonTapped:(UIButton *)button;
@end

@interface MyController : UIViewController

@property (nonatomic, assign) id <MyControllerDelegate> delegate;

- (IBAction)buttonTapped:(UIButton *)button;

@end

Then in your implementation

MyController.m

- (IBAction)buttonTapped:(UIButton *)button
{
    if ([self.delegate respondsToSelector:@selector(myController:buttonTapped:)]) {
      [self.delegate myController:self buttonTapped:button];
    }
}

As the method defined in the protocol was not optional I could have instead done a check for (self.delegate) to make sure it is set instead of respondsToSelector.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文