从子视图访问UIViewcontroller - iOS

时间:2012-07-11 04:23:22

标签: ios uiviewcontroller

我有一个UIView .xib文件。这是从故事板入口点UIViewController1作为子视图打开的。子视图有一个IBButton,当按下它时会打开一个UIViewController2。这有可能吗?

2 个答案:

答案 0 :(得分:0)

首先,创建一个从第一个视图控制器到第二个视图控制器的segue。我要命名为OpenViewController2。我们将能够以编程方式调用segue。

UIView .h文件中,创建一个定义该视图委托的协议:

SomethingView.h:

@protocol SomethingViewDelegate <NSObject> {
    - (void)importantThingHappened;
}

...

@interface SomethingView {
    id<SomethingViewDelegate> delegate;
}

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

SomethingView.m:

@implementation
@synthesize delegate;

...

// The IBAction for the button in your view
- (IBAction)buttonClicked:(id)sender {
    [delegate importantThingHappened];
}

MyViewController.m,您可以在其中创建视图:

// Create view
UIView *myView = ...

myView.delegate = self;

稍后在MyViewController中:

// Implement the protocol. This function will be called when the button action
// inside of the UIView you created is pressed
- (void)importantThingHappened {
    [self performSegueWithIdentifier:@"OpenViewController2" sender:self];
}

答案 1 :(得分:0)

首先给你的IBButton一个唯一的标签,并在你的UIViewController的viewDidLoad中,

// add following line into viewDidLoad

[(UIButton*)[self.view viewWithTag:MY_UNIQUE_TAG_FOR_BUTTON] addTarget:self action:@selector(buttonPressed:) forControlEvent:UIControlEventTouchUpInside];

最后实现buttonPressed:无论你想要什么

-(void) buttonPressed:(UIButton*)aButton {
    // do what you want to do.
}