从其他视图控制器调用按钮

时间:2014-07-03 11:16:30

标签: ios uibutton

当点击第一个视图控制器中的按钮时,如何调用第二个视图控制器中的按钮(假事件)?

我可以通过执行以下操作来伪造相同视图控制器中的按钮的事件:

- (IBAction)first:(id)sender {
    NSLog(@"this is second");
}

- (IBAction)second:(id)sender {
     [self.first sendActionsForControlEvents:UIControlEventTouchUpInside];   // works
}

但如果按钮位于不同的视图控制器中,我就无法伪造它:

- (IBAction)first:(id)sender {
   SecondViewController *SecondView = [[ViewController alloc] init];
   [SecondView.button sendActionsForControlEvents: UIControlEventTouchUpInside]; // doesnt work

}

1 个答案:

答案 0 :(得分:0)

假设您的第二个VC归第一个VC所有,那么

a)将这样的属性添加到FirstViewController的类扩展名中,例如:

#import "SecondViewController.h"

@interface FirstViewController()
// Be aware of retain cycles.
@property (nonatomic, retain) SecondViewController *secondVC;
@end

b)创建SecondViewController时,将其存储在我们刚刚创建的属性中:

// Change this if you're not using a Storyboard.
self.secondVC = [[UIStoryboard storyboardWithName:@"MainStoryboard"
                                           bundle:nil]
          instantiateViewControllerWithIdentifier:@"SecondViewController"];

c)向SecondViewController添加方法:

- (void)clickMyButton:(id)sender {
     [self.myButton sendActionsForControlEvents:UIControlEventTouchUpInside];
}

d)通过FirstViewController

实现目标
[self.secondVC clickMyButton:self];

如果我的第一个假设不正确,您仍然可以执行步骤A,B和D.步骤B稍作更改:您必须将self.secondVC设置为在其他位置创建的现有实例。

相关问题