我面临与委派相关的问题。我有 2 个 tabView。在第一个选项卡视图中,我有 2 个文本字段和一个按钮(用于触发委托方法),在第二个选项卡视图中,我有 2 个标签来显示第一个选项卡视图中文本字段的内容。我的代码有什么问题???
对于第一个 tabviewA .h 文件
#import <UIKit/UIKit.h>
@class ViewControllerA;
@protocol ViewControllerADelegate <NSObject>
-(void)sayHello:(ViewControllerA*)viewController;
@end
@interface ViewControllerA : UIViewController<UITextFieldDelegate>
@property (nonatomic,strong)IBOutlet UITextField *textFieldFirst;
@property (nonatomic,strong)IBOutlet UITextField *textFieldSecond;
@property (nonatomic,strong)id<ViewControllerADelegate>delegate;
-(IBAction)next:(id)sender;
@end
和 .m 文件
#import "ViewControllerA.h"
@interface ViewControllerA ()
@end
@implementation ViewControllerA
@synthesize textFieldFirst=_textFieldFirst;
@synthesize textFieldSecond=_textFieldSecond;
@synthesize delegate=_delegate;
- (void)viewDidLoad
{
[super viewDidLoad];
_textFieldFirst.delegate=self;
_textFieldSecond.delegate=self;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return NO;
}
-(IBAction)next:(id)sender
{
[self.delegate sayHello:self];
}
@end
而对于第二个 tabbarViewB 的 .h 文件
#import <UIKit/UIKit.h>
#import "ViewControllerA.h"
@interface ViewControllerB : UIViewController<ViewControllerADelegate>
@property (nonatomic,strong)IBOutlet UILabel *labelFirst;
@property (nonatomic,strong)IBOutlet UILabel *labelSecond;
@end
和 .m 文件
#import "ViewControllerB.h"
@interface ViewControllerB ()
@end
@implementation ViewControllerB
@synthesize labelFirst=_labelFirst;
@synthesize labelSecond=_labelSecond;
- (void)viewDidLoad
{
[super viewDidLoad];
ViewControllerA *viewControllerA=[self.tabBarController.viewControllers objectAtIndex:0];
viewControllerA.delegate=self;
// Do any additional setup after loading the view.
}
-(void)sayHello:(ViewControllerA *)viewController
{
_labelFirst.text=viewController.textFieldFirst.text;
_labelSecond.text=viewController.textFieldSecond.text;
}
@end
注意:我已经尝试使用相同的过程将 tabView B 转换为 tabview A,并且效果很好。反向(即从 A 到 B)根本不起作用。谢谢