用属性进行传值,将A界面的值传递到B界面。在B类中定义一个变量,然后在A类中跳转到B类中的地方,对需要传递的变量进行赋值。
在A界面中代码
#import "AViewController.h"
#import "BViewController.h"
@interface AViewController ()
@property (retain, nonatomic)UITextField *textField;
@end
@implementation AViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"属性正向传值";
_textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 70, self.view.frame.size.width-20, 40)];
_textField.placeholder = @"请输入一个值";
_textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:_textField];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50, 150, self.view.frame.size.width-100, 30)];
btn.backgroundColor = [UIColor greenColor];
[btn setTitle:@"确定" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
-(void)btnClick:(id)sender
{
BViewController *BVC = [[BViewController alloc] init];
BVC.string = _textField.text;
[self.navigationController pushViewController:BVC animated:YES];
}
在B界面中代码
#import <UIKit/UIKit.h>
@interface BViewController : UIViewController
@property (retain,nonatomic) NSString *string;
@end
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 64, self.view.frame.size.width-20, 40)];
lab.backgroundColor = [UIColor redColor];
NSString *str = [NSString stringWithFormat:@"%@:%@",@"你传的值为",_string];
lab.text = str;
[self.view addSubview:lab];
}
当然最后还是值得注意是,一般我们会另外创建两个视图,需要在AppDelegate.m中做连接
#import "AppDelegate.h"
#import "AViewController.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
AViewController *AVC = [[AViewController alloc] init];
UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:AVC];
self.window.rootViewController = navigation;
return YES;
}
效果图: