我有一个带有UIViewController
的{{1}},它创建了一个我希望传递给我的RootViewController( BL_MainViewController )的字符串。
我的策略是使用委托模式,但我无法弄清楚我在哪里出错了。如果我的RootViewController是使用Storyboard创建的,我如何告诉它 BL_MainViewController.BL_SetTimerViewController = self 我在哪里设置它(猜测:ViewDidLoad)?
BL_SetTimerViewController.h (IB中由模态segue呈现的子VC)
UIPickerView
BL_SetTimerViewController.m
@protocol BL_SetTimerViewControllerDelegate
-(void) updateLabelWithString:(NSString *)string;
@end
@interface BL_SetTimerViewController : UIViewController{
... // some ivars
}
@property (assign, nonatomic) id <BL_SetTimerViewControllerDelegate> delegate;
@end
BL_MainViewController.h (根VC)
@implementation BL_SetTimerViewController
...
@synthesize delegate;
...
- (IBAction)setTimerAndDismissViewController:(id)sender {
// does some stuff, then:
[self.delegate updateLabelWithString:@"TEST"];
[self dismissViewControllerAnimated:YES completion:nil];
}
BL_MainViewController.m
#import "BL_SetTimerViewController.h"
@interface BL_MainViewController : UIViewController <BL_SetTimerViewControllerDelegate>{
...
}
@end
答案 0 :(得分:0)
在你的BL_MainViewController.m
中- (void)viewDidLoad {
[super viewDidLoad];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.pLabel.text=GlobleSting;
}
-(void)updateLabelWithString:(NSString *)string {
GlobleSting = string; //declare in .h file
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"YoursegueIdentifir"]) {
BL_SetTimerViewController *settimerVC =
segue.destinationViewController;
settimerVC.delegate = self;
}
}
答案 1 :(得分:0)
代表的超级简单测试应用程序(注意很多东西都被遗漏了,因为它很快被抛到一起),这对我有用。(请注意,委托很弱,不能分配。如果你的目标是iOS 5+ ,使用弱代表)
SimpleProtocol.h
@protocol SimpleProtocol <NSObject>
- (void)updateText:(NSString *)text;
@end
ViewController.m
#import "ViewController.h"
#import "SecondViewController.h"
#import "SimpleProtocol.h"
@interface ViewController ()<SimpleProtocol>
@property (nonatomic, weak) IBOutlet UILabel *label;
@end
@implementation ViewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
SecondViewController *vc = (SecondViewController *)segue.destinationViewController;
vc.delegate = self;
}
- (void)updateText:(NSString *)text
{
self.label.text = text;
}
@end
SecondViewController.m
#import "SimpleProtocol.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerFire:) userInfo:nil repeats:NO];
}
- (void)timerFire:(NSTimer *)timer
{
NSString *text = [NSString stringWithFormat:@"Test %@", @(arc4random())];
[self.delegate updateText:text];
[self.navigationController popViewControllerAnimated:YES];
}
@end