UI中的属性传值,方法传值和协议传值

来源:互联网 发布:ai 人工智能 影评 编辑:程序博客网 时间:2024/06/05 12:48

UI中的属性传值,方法传值和协议传值:

一.属性传值

       在MainViewController与SecondViewController两个视图控制器中,点击MainViewController中的button按钮将跳转到SecondViewController视图控制器中,同时可以利用属性传值传递一个值过去。

       首先SecondViewController视图中需要有一个属性用来存储传递过来的值:

@property(nonatomic,retain) NSString *firstValue;//属性传值

       然后MainViewController视图需要引用SecondViewController视图的头文件,在视图中的按钮点击事件中,通过SecondViewController</span>的对象将需要传递的值存在firstValue中:

-(void)buttonAction:(UIButton *)button{SecondViewController *second = [[SecondViewController alloc]init];//用下一个视图的属性接受想要传过去的值,          属性传值second.firstValue = _txtFiled.text;[self.navigationController pushViewController:second animated:YES];[second release];}

点击跳转到SecondViewController视图中,通过存值的属性,取用刚才传递过来的值:

       [_txtFiled setText:_firstValue];//firstValue保存传过来的值

二.方法传值

需求同一中的属性传值一样,但是要通过使用方法传值,可以直接将方法与初始化方法合并,此时当触发MainViewController的按钮点击事件并跳转到SecondViewController时,在按钮点击事件中可以直接通过SecondViewController的初始化,将值保存在firstValue中:

初始化方法如下:

//重写初始化方法,用于传值- (id)initWithValue:(NSString *)value{if(self = [super initWithNibName:nil bundle:nil]){self.firstValue = value;}return self;}

二.方法传值:

- (void)buttonAction:(UIButton *)button{//将方法传值与初始化写到一起

SecondViewController *second = [[SecondViewController alloc]initWithValue:_txtFiled.text];//此时已经将值存在firstValue中                       [self.navigationController pushViewController:second animated:YES];[second release];

}

这样就可以直接通过firstValue属性获得传递过来的值:

        [_txtFiled setText:_firstValue];//firstValue保存传过来的值

三.协议传值

1、在需要传值给其他类的类头文件中定义一个协议。

@protocol stringDelegate<NSObject>
-(void)textField:(NSString *)sender;
@end

2、在该类中声明一个代理属性:

@property (assign,nonatomic)id<stringDelegate>delegate;//设置代理人

3、在.m文件中实现:

@synthesize delegate ;

4、在需要触发传值的方法中调用协议中的方法:

[delegate textField:aTextField.text];

5、在传值给的类中的.h文件文件中引用该协议:

@interface rootViewController : UIViewController<stringDelegate>

6、在.m文件中:

secondViewController = [[SecondViewController alloc]init];
    secondViewController.delegate = self;

7、然后实现该方法:

-(void)textField:(NSString *)sender
{
    aLabel.text = sender;
}


0 0