我正在学习 objective-c ,需要帮助来理解委托(delegate)。
我在 FirstViewController 中有一个 UITextField,我想显示在 SecondViewController 中输入的文本。
但它不起作用。我究竟做错了什么?
这是我的代码:
第一 View Controller .h
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIButton *accessButton;
@property (weak, nonatomic) IBOutlet UITextField *codeField;
@property (nonatomic, retain) NSString *getCodeString;
@end
SecondViewController.h
#import <UIKit/UIKit.h>
@class CodeField;
@protocol CodeFieldHandlerDelegate <NSObject>
@property NSString *saveCodeString;
@end
@interface SecondViewController : UIViewController
@property (weak, nonatomic) IBOutlet UILabel *candidateLabel;
@property (weak, nonatomic) id <CodeFieldHandlerDelegate> myDelegate;
@end
第一 View Controller .m
#import "FirstViewController.h"
#import "SecondViewController.h"
@interface FirstViewController ()
<CodeFieldHandlerDelegate>
@property (nonatomic, strong) SecondViewController *secondViewController;
@end
@implementation FirstViewController
@synthesize getCodeString;
@synthesize secondViewController;
@synthesize saveCodeString;
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)accessButton:(UIButton *)sender {
//get the input data from text field and store into string
getCodeString = self.codeField.text;
//go keypad back when button clicked from textfield
[self.codeField resignFirstResponder];
secondViewController = [[SecondViewController alloc] init];
secondViewController.myDelegate = self;
[self.navigationController pushViewController:secondViewController animated:YES];
}
// name of this string is the same of the NSString in the delegate
- (NSString *) saveCodeString {
return getCodeString;
}
@end
和 SecondViewController.m
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
@synthesize candidateLabel;
@synthesize myDelegate;
- (void)viewDidLoad {
[super viewDidLoad];
self.candidateLabel.text = [myDelegate saveCodeString];
}
@end
最佳答案
我相信您正在对 SecondViewController
进行转场。错误的方法。你有没有得到 FirstViewController
的转场?到SecondViewController
在职的?
试试这个:
secondViewController = (SecondViewController *)[[UIStoryboard storyboardWithName:@"YOUR STORYBOARD NAME" bundle:nil] instantiateViewControllerWithIdentifier:@"YOUR CONTROLLER IDENTIFIER"];
关于ios - 带有委托(delegate)的 objective-c 文本字段不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32513570/