简体   繁体   English

从子视图访问UIViewcontroller-iOS

[英]Accessing UIViewcontroller from a subview - iOS

I have a UIView .xib file. 我有一个UIView .xib文件。 This is opened from the storyboard entry point UIViewController1 as a subview. 这是从情节提要入口点UIViewController1作为子视图打开的。 The subview has a IBButton which when pressed opens a UIViewController2. 子视图具有IBButton,按下该按钮将打开UIViewController2。 Is this possible by any chance? 这有可能吗?

First, create a segue going from your first view controller to your second. 首先,创建从第一个视图控制器到第二个视图控制器的序列。 I'm going to name it OpenViewController2 . 我将其命名为OpenViewController2 We'll be able to call that segue programmatically. 我们将能够以编程方式调用该序列。

In your UIView .h file, create a protocol that defines a delegate for that view: 在您的UIView .h文件中,创建一个协议,为该视图定义一个委托:

SomethingView.h: SomethingView.h:

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

...

@interface SomethingView {
    id<SomethingViewDelegate> delegate;
}

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

SomethingView.m: SomethingView.m:

@implementation
@synthesize delegate;

...

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

MyViewController.m, where you create your view: MyViewController.m,在其中创建视图:

// Create view
UIView *myView = ...

myView.delegate = self;

Later in MyViewController: 稍后在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];
}

First give your IBButton an unique tag, and in your UIViewController's viewDidLoad, 首先给您的IBButton一个唯一的标签,然后在您的UIViewController的viewDidLoad中,

// add following line into viewDidLoad

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

and finally implement the buttonPressed: for whatever you want 并最终实现buttonPressed:无论您想要什么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM