代码改变世界

属性传值

2016-04-22 14:41  甘雨路  阅读(239)  评论(0编辑  收藏  举报
#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;


@end
#import "AppDelegate.h"
#import "RootViewController.h"
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    //初始化导航控制器
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:[[RootViewController alloc] init]];
    self.window.rootViewController = navi;
    
    [self.window makeKeyAndVisible];
    return YES;
}


@end
#import <UIKit/UIKit.h>

@interface RootViewController : UIViewController

@end
#import "RootViewController.h"
#import "LFViewController.h"
@interface RootViewController ()

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //添加按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(100, 100, 150, 60);
    [button setTitle:@"跳到下一个页面" forState:0];
    [button setBackgroundColor:[UIColor greenColor]];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

/**
 *  按钮事件
 */
- (void)buttonAction:(UIButton*)sender{
    /**
     *  属性传值,从一个控制器push到下一个控制器使用属性传值比较方便
     */
    LFViewController *lfController = [[LFViewController alloc] init];
    //把值传给LFViewController中的CityName
    lfController.cityName = @"北京";
    [self.navigationController pushViewController:lfController animated:YES];
}

@end
#import <UIKit/UIKit.h>

@interface LFViewController : UIViewController

@property(nonatomic , strong) NSString *cityName;//设置属性

@end
#import "LFViewController.h"

@interface LFViewController ()

@end

@implementation LFViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //打印cityName的值
    NSLog(@"cityName:%@",self.cityName);
    UILabel *cityNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 150, 60)];
    cityNameLabel.backgroundColor = [UIColor redColor];
    //显示城市的名字
    cityNameLabel.text = self.cityName;
    cityNameLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:cityNameLabel];
}

@end