我想用纯代码在viewController之间创建UI练习块传递值。但回调块不起作用。 NSLog方法没有打印任何东西在调试区域。这是代码。给我一些提示,谢谢。iOS Objective-C块回调问题
VC.h
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
@property (copy, nonatomic) void (^callBack)(NSString *text);
@end
VC.m
- (UITextField *)textField {
if (!_textField) {
_textField = [[UITextField alloc] init];
_textField.backgroundColor = [UIColor whiteColor];
}
return _textField;
}
- (UIButton *)button {
if (!_button) {
_button = [[UIButton alloc] init];
_button.backgroundColor = [UIColor blueColor];
[_button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
}
return _button;
}
- (void)setupUI {
[self.view addSubview:self.textField];
[self.view addSubview:self.button];
[self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(200);
make.height.mas_equalTo(50);
make.centerX.mas_equalTo(self.view.mas_centerX);
make.centerY.mas_equalTo(self.view);
}];
[self.button mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(200);
make.height.mas_equalTo(50);
make.centerX.mas_equalTo(self.view);
make.centerY.mas_equalTo(self.view).offset(100);
}];
}
- (void)buttonAction {
NSString *str = self.textField.text;
if (self.callBack != nil) {
self.callBack(str);
NSLog(@"This statement didnt print in log");
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[self setupUI];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor redColor];
}
更新代码
VC2.m
- (void)viewWillAppear:(BOOL)animated{
self.callBack = ^(NSString *text){
};
}
- (void)buttonAction {
if (self.callBack) {
NSLog(@"It worked on debug area %@", self.textField.text);
self.callBack(self.textField.text);
}
self.textField.text = @"";
}
VC1.m
- (void)viewDidLoad {
[super viewDidLoad];
_secondVc = [[SecondViewController alloc] init];
_secondVc.callBack = ^(NSString *str){
};
[self setupUI];
self.view.backgroundColor = [UIColor greenColor];
}
- (void)viewWillAppear:(BOOL)animated {
if (_secondVc.callBack != nil) {
NSLog(@"It wrked on debug screen");
_secondVc.callBack = ^(NSString *str){
NSLog(@"It didn't worked on debug screen");
//I want set my label.text = str;
};
};
}
您的'callBack'是无开始。我建议你看看这个例子来更多地了解Objective-C块。 http://www.appcoda.com/objective-c-blocks-tutorial/ – KrishnaCA
thx为你的链接,我已修复它。你有任何其他块和快速关闭教程链接或视频? – Haixiao
我在第二个viewDidLoad中初始化回调块。secondViewController工作,但我不能从firstViewController调用它,如何在firstVC中调用它。 – Haixiao