使用另一个UIViewController的IBAction iOS调用一个UIControllerView的IBAction

时间:2015-08-24 04:49:55

标签: ios objective-c

我在一个应用程序上工作,我想使用另一个UIControllerView调用一个UIControllerView的IBAction,请帮助我如何实现它。

假设, 我有两个名为FirstViewContoller和SecondViewController的UIViewController,现在我在FirstViewController中有一个IBAction,在SecondViewController中有另一个IBAction,现在我想在点击FirstViewControllers IBAction时使用SecondViewControllers IBAction。

我如何实现这种工作。

代码片段会很明显。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以使用代理

执行此操作

在FirstViewController.h中

@protocol myDelegate <NSObject>

-(void)changeValue;

@end

@interface FirstViewController : UIViewController

@property (nonatomic,weak) id <myDelegate>delegate;

AND SecondViewController.h

#import "FirstViewController.h"

@interface SecondViewController : UIViewController<myDelegate>

再次在SecondViewController.m的Outlet操作方法

-(IBAction)mySecondViewControllerOutlet:(id)sender{
  FirstViewController *v = [[FirstViewController alloc]init];
   [v.delegate changeValue ];
}

最后在FirstViewController.m

 -(void)changeValue{
//Write down the change of code you want to implement
}

希望这有帮助。

答案 1 :(得分:0)

对于你解释的情况“实际上我必须将我的工作代码放在第二个vc中,我在第一个vc上有按钮,所以我想在第一个vc中点击按钮时使用第二个vc的IBAction。“这是你可以做到的。

//this if from FirstVC
@IBAction func doSomething(sender:UIButton!){
let computedThing  = SecondViewController().computeThisThing()
//do what your app needs now
 }

请记住在SecondViewController上具有确切的方法和返回类型。 SecondViewControllers ibaction看起来像这样

//This is from the Second VC
@IBAction func doSomethingHere(sender:UIButton!){
let computedThing  = computeThisThing()
//do what your app needs now
}

func computeThisThing() ->String {  //or whatever data type is required
//do some work
return "something"
}

但我建议你,将公共代码重构为一个单独的类并使用它。这使得架构设计牢固,并遵循单一对象单一责任设计模式。

如果这有帮助,请告诉我。干杯!