【问题标题】:Call IBAction of one UIControllerView using another UIViewController's IBAction iOS使用另一个 UIViewController 的 IBAction iOS 调用一个 UIControllerView 的 IBAction
【发布时间】:2015-08-24 04:49:54
【问题描述】:

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

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

我怎样才能实现这种工作。

代码 sn-ps 将是可观的。

提前致谢。

【问题讨论】:

  • 第二个vc的outlet的动作到底想做什么?设置一些值,如果你能说出来或清楚,那会有所帮助。
  • 实际上我必须将我的工作代码放在第二个 vc 中,并且我在第一个 vc 上有按钮,所以当我点击第一个 vc 中的按钮时,我想使用第二个 vc 的 IBAction。
  • 你想调用SecondVC上的方法还是触发代码触摸。如果你需要第一个,它很容易。您需要做的就是 SecondVC().myMethod() 但它有点不清楚是否是第二种情况。
  • 我知道这是我已经完成的复杂代码。还有更多选择可以让它变得简单,但现在我没有时间更改代码,所以我需要发布这个问题。

标签: ios objective-c


【解决方案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
}

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    对于您解释的情况“实际上我必须将我的工作代码放在第二个 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"
    }
    

    但我会建议您将公共代码重构为单独的类并使用它。这使得架构设计更加稳固,并遵循单一对象单一职责设计模式。

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

    【讨论】:

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