从Home View Controller中的模态View Controller中访问UITextField中的文本

时间:2013-08-10 02:20:08

标签: ios objective-c uitextfield

我有一个ViewController1 UILabel可以提供ViewController2模态瞄准。我需要UITextField ViewController2 ViewController1UILabel我需要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]; } 中使用的代码:

VCProtocol

ViewController1.h

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; } } 中的{{1}}。然后,在我的{{1}}中,我有这段代码:

{{1}}

2 个答案:

答案 0 :(得分:0)

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

为您的segue(故事板)提供标识符,并实施prepareForSegue,如下所示:

VC2Delegate.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是否被召唤?
  • 如果是,委托方法是否被调用?
  • 如果未调用委托方法,请检查委托是否为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];
}

答案 1 :(得分:-2)

I ran into this problem时,我选择了单身方法并且有效。