【问题标题】:Create IBAction of UIButton in one view controller and influence the action in another view controller在一个视图控制器中创建 UIButton 的 IBAction 并影响另一个视图控制器中的操作
【发布时间】:2015-08-01 22:17:16
【问题描述】:

我打算创建两个 UIViewController。基本上,两个视图控制器之一中有一些按钮。当我按下其中一个按钮时,我想在另一个视图控制器中触发一些动作。有没有办法让它成为可能?

【问题讨论】:

  • 使用委托方法。
  • 在addTarget方法中,放入另一个viewcontroller。

标签: ios objective-c uiviewcontroller uibutton ibaction


【解决方案1】:

是的,您可以为此使用委托。

例如,你可能有这个 ViewControllers。

//FirstViewController.h

@protocol ProtocolName <NSObject>

  - (void)doSomething;

@end

@interface FirstViewController

 @property (nonatomic, strong) id<ProtocolName> delegate;

 @property (weak, nonatomic) IBOutlet UIButton *button;

 - (IBAction)action:(id)sender;

@end

这里我们需要一个协议,它定义了一个或多个要在任何实现该协议的对象中实现的方法。而且我们还需要一个委托,即实现此协议的对象(在本例中称为“ProtocolName”,但您可以随意命名)。

然后是第二个 ViewController

//SecondViewController.h
#import "FirstViewController.h" //Need this to reference protocol

@interface SecondViewController <ProtocolName>

@end

我们说 SecondViewController 将实现 ProtocolName 协议,所以在他的 .m 文件中我们需要这样做。

//SecondViewController.m

- (void)doSomething{
  //Do something
}

魔法来了。

假设当您点击 FirstViewController 中的按钮时,它会触发 SecondViewController 中的 doSomething 方法。所以,你需要做这样的事情。

//FirstViewController.m

//...
SecondViewController secondVC = [[SecondViewController alloc] init];
this.delegate = secondVC; //DON'T FORGET THIS
//...

- (IBAction)action:(id)sender{ 
 [this.delegate doSomething];
}

这就是委托模式。

【讨论】:

    【解决方案2】:

    有这么三种可能的方法来做到这一点,

    使用NSNotificationCenter,使用Delegates,最后一个使用Blocks,第一个选项好学。

    1. 将观察者添加到 FirstViewController
    2. 在 SecondViewController 中发布通知(当用户单击按钮时)

    参考this link

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多