在IOS里两个UIView窗口之间传递参数方法有很多,比如
1.使用SharedApplication,定义一个变量来传递.
2.使用文件,或者NSUserdefault来传递
3.通过一个单例的class来传递
4.通过Delegate来传递。
这次主要学习如何使用通过Delegate的方法来在不同的UIView里传递数据 。
比如: 在窗口1中打开窗口2,然后在窗口2中填入一个数字,这个数字又回传给窗口1。
窗口1
窗口2
窗口2的结果传递给窗口1
工程截图:
窗口一:
//
// ViewController.h
// DelegateDemo
//
// Created by Fox on 12-3-21.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
//定义一个协议用来传值
@protocol UIViewPassValueDelegate
- (void)passValue:(NSString *)value;
@end
//实现协议
@interface ViewController : UIViewController <UIViewPassValueDelegate>{
}
@property (retain, nonatomic) IBOutlet UITextField *texta;
- (IBAction)openPress:(id)sender;
@end
//
// ViewController.m
// DelegateDemo
//
// Created by Fox on 12-3-21.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import "ViewController.h"
#import "ViewBController.h"
@implementation ViewController
@synthesize texta;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[self setTexta:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (IBAction)openPress:(id)sender {
ViewBController *viewb = [[ViewBController alloc] initWithNibName:@"ViewBController" bundle:nil];
viewb.delegate = self;
[self setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
[self presentModalViewController:viewb animated:YES];
}
- (void)dealloc {
[texta release];
[super dealloc];
}
//实现协议的方法
#pragma mark UIViewPassValueDelegate mothod
- (void)passValue:(NSString *)value
{
self.texta.text = value;
NSLog(@"the get value is %@", value);
}
@end
窗口二:
//
// ViewBController.h
// DelegateDemo
//
// Created by Fox on 12-3-21.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ViewController.h"
@interface ViewBController : UIViewController{
NSObject<UIViewPassValueDelegate> *delegate;//定义协议
}
@property (retain, nonatomic) IBOutlet UITextField *text;
@property (retain, nonatomic) NSObject<UIViewPassValueDelegate> *delegate;
- (IBAction)buttonpress:(id)sender;
@end
//
// ViewBController.m
// DelegateDemo
//
// Created by Fox on 12-3-21.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import "ViewBController.h"
@implementation ViewBController
@synthesize text;
@synthesize delegate;
- (void)dealloc {
[text release];
[super dealloc];
}
- (IBAction)buttonpress:(id)sender {
[delegate passValue:self.text.text];//调用协议的方法
NSLog(@"self.value.text is%@", self.text.text);
[self dismissModalViewControllerAnimated:YES];
}
@end
参考来自:http://www.cnblogs.com/likwo/archive/2011/03/02/1968785.html