IOS传值方法-属性正向传值

本文介绍了如何通过属性在iOS应用中实现从A界面到B界面的值传递。在B类定义变量,并在A类的跳转代码中对变量进行赋值。同时,为确保视图间的正确连接,通常需要在AppDelegate.m中进行相应配置。
摘要由CSDN通过智能技术生成

用属性进行传值,将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;
}

效果图:

这里写图片描述

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值