[英]Accessing UIViewcontroller from a subview - iOS
我有一個UIView .xib文件。 這是從情節提要入口點UIViewController1作為子視圖打開的。 子視圖具有IBButton,按下該按鈕將打開UIViewController2。 這有可能嗎?
首先,創建從第一個視圖控制器到第二個視圖控制器的序列。 我將其命名為OpenViewController2
。 我們將能夠以編程方式調用該序列。
在您的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];
}
首先給您的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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.