2017-03-28 3 views
-3

ストーリーボードなしでiOSアプリケーションを作成し、AppDelegateでウィンドウのフレームを設定しています。非ベースのストーリーボードアプリケーションのViewController間でデータを渡す

今、ViewControllerとSettingsControllerの2つのView Controllerがあります。設定コントローラでは、myTextField.textを変数に格納するテキストフィールド(myTextField)を作成しました。 どうすればいいですか?

+1

Googleで最初に検索し、基本的な概念を学ぶ。 –

+1

私はストーリーボードでこれを行う方法を知っていますが、インターネット上で何も見つけることができないと、どうして私はあなたの助けに感謝する方法を知っています。 – TBDevOfWorldOfSwIFT

+0

私の答えをチェックしてください。 –

答えて

0

あなたはAppDelegateファイル内のパブリックプロパティを作成することができ、

@property(nonatomic,strong) NSString *passingText; 

1のViewController 2インポートAppdelegate:

@interface viewcontroller2() 
    { 
    AppDelegate *appdelegate; 
    } 
    @end 

    - (void)viewDidLoad 
    { 
    appdelegate = (AppDelegate *)[UIApplication SharedApplication].delegate; 
    } 
    Once user entered text in myTextField, using delegate: 

    - (void)textFieldDidEndEditing:(UITextfield *)textField 
    { 
    appdelegate.passingText = textField.text; 

    } 

は、第二のコントローラであなたがappdelegateの値を読み取ることができます。

これは、あなたの要件を解決するのに役立ちます。

+0

はカスタムプロトコルに基づいており、VC2からVC1 –

-2

SecondViewController.h

#import <UIKit/UIKit.h> 

@protocol SecondViewControllerDelegate <NSObject> 

@optional 
- (void)secondViewDidEndEditingText:(UITextField *)textField; 

@end 

@interface SecondViewController : UIViewController 

@property (nonatomic, weak) id<SecondViewControllerDelegate> delegate; 

@end 

SecondViewController.m

#import "SecondViewController.h" 

@interface SecondViewController()<UITextFieldDelegate> 
@property (nonatomic, strong) UITextField *textField; 
@end 

@implementation SecondViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 

    [self textField]; 
} 

- (UITextField *)textField 
{ 
    if (!_textField) { 
     _textField = [[UITextField alloc] initWithFrame:CGRectMake(100, 50, 80, 40)]; 
     _textField.delegate = self; 
     [self.view addSubview:_textField]; 
    } 
    return _textField; 
} 

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
    if ([self.delegate respondsToSelector:@selector(secondViewDidEndEditingText:)]) { 
     [self.delegate secondViewDidEndEditingText:textField]; 
    } 
} 

@end 

ViewController.m

#import "ViewController.h" 
#import "SecondViewController.h" 
@interface ViewController()<SecondViewControllerDelegate> 

@end 

@implementation ViewController 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
} 

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 
{ 
    SecondViewController *secondVC = [SecondViewController new]; 
    secondVC.delegate = self; 
    [self presentViewController:secondVC animated:YES completion:NULL]; 
} 

- (void)secondViewDidEndEditingText:(UITextField *)textField 
{ 
    NSLog(@"SecondViewControllerText:%@", textField.text); 
} 


@end 
+0

はVC2からVC1にデータを渡すカスタムプロトコルに基づいています –

+0

この最初のコードスニペットは間違っています。また、View Controller間でデータを渡す目的でUserDefaultsを使用することは、まったく良いアイデアではありません。 –

+0

私の英語は良くないので、私は彼の質問を理解していない、今理解する。私は自分の答えを再編集しました。ここでの – zzqiltw

関連する問題