我在尝试将数据从一个viewcontroller上的两个UITextfields传递到另一个viewcontroller时有点困惑。基本上我得到了以下项目:
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
IBOutlet UITextfield *Textfield1;
IBOutlet UITextfield *Textfield2;
}
-(IBAction)GoNextView:(id)sender;
@end
ViewController.m
@interface ViewController ()
@end
@implementation ViewController
(IBAction)GoNextView:(id)sender {
SecondView *second = [[SecondView alloc] initWithNibName:nil bundle:nil];
[self presentViewController:second animated:YES completion:NULL];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
SecondView.h
#import <UIKit/UIKit.h>
@interface SecondView : UIViewController {
IBOutlet UILabel *ShowTextfield1;
IBOutlet UILabel *ShowTextfield2;
}
-(IBAction)GoBack:(id)sender;
@end
SecondView.m
@interface SecondView ()
@end
@implementation SecondView
- (IBAction)GoBack:(id)sender {
[self dismissViewControllerAnimated:YES completion:NULL];
}
我想要的是,当按下按钮GoNextView
时,它应该将UITextfield
中的数据传递给SecondView
。然后转到下一页。现在,数据应显示在SecondView
的两个标签中。我已经在这个问题上苦苦挣扎了好几个小时,这让我很伤心。我知道我必须使用一些NSString
和@property(nonatomic, retain) NSString *asdas
。但我根本无法使其发挥作用。因此,基于上面的代码,如何将数据从两个UITextfield
传递到下一个视图中的两个标签?
答案 0 :(得分:0)
不使用功能导航到第二个视图,而是使用Storyboard Segues。创建一个storybaord应用程序。要创建segue,您需要一个导航视图控制器。您可以通过以下步骤完成此操作。
现在,在SecondView.h中创建两个字符串,
@property (nonatomic, retain) NSString *str1;
@property (nonatomic, retain) NSString *str2;
并在SecondView.m中合成它们。
让我们将您的UITextField命名为ViewController中的“text1”和“text2”。转到ViewController.h并添加#import "SecondView.h"
在ViewController.m中执行以下操作,
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"connector"])
{
ViewController *VC = [segue destinationViewController];
VC.str1 = text1.text;
VC.str2 = text2.text;
}
}
现在您可以在SecondView中显示这些字符串。在Secondview.m中,
label.text = str1;
将显示。
答案 1 :(得分:0)
使用NSUserDefaults或常规合成通用接口变量。例如,
<强> NSUserDefaults的强> 来自发件人的视图控制器,
NSString * text = textField1.text; NSUserDefaults * prefs = [NSUserDefaults standardUserDefaults]; [prefs setObject:text forKey:@&#34; text1value&#34;];
您可以从任何视图控制器获取值,
NSUserDefaults *prefs=[NSUserDefaults standardUserDefaults];
NSString *received string= [prefs stringForKey:@"text1value"];
我相信您必须使用performsegue来导航视图控制器。有一种名为&#34; prepareforsegue&#34;您可以将文本字段值分配给接口变量。例如,
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"seguename"]) {
destViewController *destViewController = segue.destinationViewController;
destViewController.name = @"some text";
}
}
在接收器的视图控制器中,getter变量实际上定义为,
在.h文件中,@property(nonatomic, strong) NSString *name;
在.m文件中,不要忘记在实现后合成变量
@implementation destViewController
@synthesize name;
希望它有所帮助!