【发布时间】:2013-08-10 02:20:07
【问题描述】:
我有一个ViewController1 和一个UILabel,它可以呈现一个带有模态搜索的ViewController2。我在ViewController2 中有一个UITextField,我需要从ViewController1 访问它,因此我可以使用收集的文本设置我的UILabel。
我尝试过使用prepareForSegue,但没有成功。我该怎么办?
编辑:
我正在使用委托,但我做错了什么。这是我在ViewController2.h 中使用的代码:
@class ViewController2;
@protocol VCProtocol
-(void)setName:(NSString *)name;
@end
@interface ViewController2 : UIViewController
@property (nonatomic, weak) id<VCProtocol> delegate;
@property (strong, nonatomic) IBOutlet UITextField *nameField;
- (IBAction)setButton:(id)sender
@end
ViewController2.m
-(IBAction)setButton:(id)sender
{
[self.delegate setName:nameField.text];
}
我的ViewController1.h 符合VCProtocol。然后,在我的ViewController1.m 中,我有这个代码:
- (void)setName:(NSString *)name
{
self.firstSignatureNameLabel.text = name;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqual:@"Sign"])
{
ViewController2 *VC = [segue destinationViewController];
VC.delegate = self;
}
}
【问题讨论】:
-
如果您希望每个视图都可以访问它,您需要创建一个模型/数据类。这个问题不是重复的,但答案适用于this question。 This question might be more like yours
-
这就是代表的用途。 VC1 在进行演示时应将自己设置为 VC2 的代理。 VC2 应该使用一个方法定义一个协议,您可以在文本字段的操作方法中调用委托。
标签: ios objective-c uitextfield