从主视图控制器访问模式视图控制器中UITextField中的文本



我有一个带UILabelViewController1,它可以呈现一个带模态分段的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;
    }
}

您可以创建一个协议并将VC1设置为VC2的委托,使用prepareForSegue将VC1设为VC2委托应该可以工作。我知道你说它不起作用,但我不明白为什么。试试这个:

给你的segue(在故事板上)一个标识符,并实现prepareForSegue,如下所示:

VC2电报.h:

@protocol VC2Delegate
    - (void)updateLabel:(NSString *)text;
@end

VC1.h:

#import "VC2Delegate.h"
@interface VC1 : UIViewController <VC2Delegate>
    // All your stuff
@end

VC1.m:

- (void)updateLabel:(NSString *)text {
    [_label setText:text];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"YourSegueIdentifier"]) {
        VC2 * vc = [segue destinationViewController];
        [vc2 setDelegate:self];
    }
}

VC2.h:

#import "VC2Delegate.h"
@interface VC2 : UIViewController
    @property (weak, nonatomic) id<VC2Delegate>delegate;
@end

VC2.m

- (void)textWasUpdated { // or whatever method where you detect the text has been changed
    if (_delegate)
        [_delegate updateLabel:[_textView text]];
}

告诉我它是否有效。否则,甚至有人叫prepareForSegue吗?

编辑:更新了我的答案(不是你需要的)。但正如你所说,它不起作用:

  • 是否调用prepareForSegue
  • 如果是,是否调用了委托方法
  • 如果未调用委托方法,请检查委托是否不是nil

您可能想要删除segue,并使用presentViewController:animated:completion:以自己的方式呈现它,如下所示:

- (IBAction)buttonWasTapped {
    static NSString * const idModalView = @"modalView";
    static NSString * const storyBoardName = @"MainStoryBoard"
    UIStoryboard * storyboard = [UIStoryboard storyboardWithName:storyBoardName bundle:nil];
    VC2 * vc = [storyboard instantiateViewControllerWithIdentifier:idModalView];
    [vc setDelegate:self];
    [self.navigationController presentViewController:vc2 animated:YES completion:nil];
}

当我遇到这个问题时,我选择了单例方法,它很有效。

相关内容

最新更新