屬性/方法傳值
//1.後面的界面定義了一個屬性,用於保存,前一個界面,傳過來的值
//注:屬性定義成字符串還是別的類型,取決於你的需求,本例我們需要一個字符串,用於UILabel顯示
//2.後面的界面創建完畢之後,爲屬性賦值,(即:記錄需要傳遞的值)
//3.在需要使用值的地方,使用屬性記錄的值這種通過定義屬性,達到傳值的方式,稱爲屬性傳值,
//屬性傳值,一般用於從前一個界面向後一個界面傳值;
代碼如下:
[objc] view plaincopy
#import "FirstViewController.h"
#import "SecondViewController.h"
#import "UIButton+Create.h"
@interface FirstViewController ()
{
UITextField * _textField;//創建一個輸入框
}
@end
@implementation FirstViewController
- (void)dealloc
{
[_textField release];
[super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor redColor];
self.navigationItem.title = @"首頁";
/**
* 1.在第一個界面創建一個輸入框
*
*/
_textField = [[UITextField alloc]initWithFrame:CGRectMake(50, 80, 200, 30)];
_textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:_textField];
/**
* 1.創建一個UIButton,
* 2.並添加響應事件,從首頁跳轉到第二個頁面.
*/
UIButton * button = [UIButton systemButtonWithFrame:CGRectMake(100, 120, 50, 50) title:@"Push" target:self action:@selector(didClickButtonAction)];
[self.view addSubview:button];
// Do any additional setup after loading the view.
}
- (void)didClickButtonAction
{
/**
* 1.用push的方法推出下一個頁面
* 2.把首頁輸入框輸入的字符串,通過SecondViewController類的屬性NSString * text接收
* 3.從而實現把首頁輸入框輸入的字符串,傳到第二頁的UILabel上.
*/
SecondViewController * secondVC = [[SecondViewController alloc]init];
secondVC.text = _textField.text;
[self.navigationController pushViewController:secondVC animated:YES];
[secondVC release];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
[objc] view plaincopy
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)dealloc
{
[_label release];
[super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor orangeColor];
self.navigationItem.title = @"第二頁";
/**
* 1.在第二個界面創建一個UILabel
* 2.把首頁輸入框輸入的字符串,通過SecondViewController類的屬性NSString * text接收
* 3.然後通過賦值給UILabel
*/
_label = [[UILabel alloc]initWithFrame:CGRectMake(50, 80, 200, 30)];
_label.backgroundColor = [UIColor greenColor];
_label.text = self.text;
[self.view addSubview:_label];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}