iOS如何實現傳值---屬性傳值

A  ----> B 傳值

步驟:

1.給B類添加一個屬性string

2.A中聲明B對象的變量 A中直接調用B屬性 例如: B.string = @"TEST";


代碼例子:

第一步:

SecondViewController.h

//
//  SecondViewController.h
//  屬性傳值
//
//  Created by 薩斯輩的呼喚 on 14-6-13.
//  Copyright (c) 2014年 薩斯輩的呼喚. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface SecondViewController : UIViewController

// 用於接收外部傳給viewController的 值
@property (nonatomic, copy) NSString *string;
@end
SecondViewController.m
//
//  SecondViewController.m
//  屬性傳值
//
//  Created by 薩斯輩的呼喚 on 14-6-13.
//  Copyright (c) 2014年 薩斯輩的呼喚. All rights reserved.
//

#import "SecondViewController.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 120, 200, 30)];
    label.text = self.string;
    [self.view addSubview:label];
    [label release];
    
}

@end


第二步:

//
//  FirstViewController.m
//  屬性傳值
//
//  Created by 薩斯輩的呼喚 on 14-6-13.
//  Copyright (c) 2014年 薩斯輩的呼喚. All rights reserved.
//

#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(20, 120, 200, 30);
    button.backgroundColor = [UIColor redColor];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)buttonClick:(UIButton *)btn
{
    SecondViewController *secVC = [[SecondViewController alloc] init];
    [self.navigationController pushViewController:secVC animated:YES];
    secVC.string = @"adf";
    [secVC release];
}
@end



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章