iOS学习笔记6-delegate的使用

今天,总结一下iOS开发中常用到的委托(delegate)的应用。

效果图:

                   首页此时label的text为空


点击button进入第二页,通过点击第二页的button返回第一页,同时也为第一页的label的text传值

                 此时首页的效果


关键代码如下:

首先新建一个协议:

#import <Foundation/Foundation.h>

@protocol delegate <NSObject>
@optional
- (void)setTitle:(NSString *)string;

@end

FirstViewController的关键代码:

首先,FirstViewController.h里面申明继承次协议

#import <UIKit/UIKit.h>
#import "delegate.h"
@interface FirstViewController : UIViewController<delegate>
@property (retain,nonatomic) UILabel *label_1;
@end

FirstViewController.m里面的关键方法:

- (void)setTitle:(NSString *)string
{
    [label_1 setText:string];
}
- (void)StepSecond
{
    SecondViewController *secondViewController = [[SecondViewController alloc]init];
    [self presentViewController:secondViewController animated:YES completion:nil];
    secondViewController.setValuce = self;
    
}
SecondViewController.h里的关键代码:

#import <UIKit/UIKit.h>
#import "delegate.h"
@interface SecondViewController : UIViewController

@property (retain,nonatomic) id<delegate>setValuce ;
@end

SecondViewController.m的关键代码
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor orangeColor];
    UILabel *label_2 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 50)];
    label_2.center = CGPointMake(160, 200);
    [label_2 setText:@"Second Page"];
    label_2.backgroundColor = [UIColor grayColor];
    [self.view addSubview:label_2];
    
    UIButton *button_2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button_2.frame =CGRectMake(0, 0, 50, 40);
    button_2.center = CGPointMake(160, 380);
    [button_2 addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button_2];
}

- (void)back
{
    [self.setValuce setTitle:@"FirstPage1"];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
总结过程:

要利用delegate进行传值,具体工程如下:

首先,需要新建一个protocol,在里面申明协议名和需要遵守的方法

其次,在需要代理对象里面执行三个关键步骤:

1 声明继承前面新建的协议

2 具体实现协议声明的方法

3 代理名.delegate = self(及理解为申明需要找代理的类的代理对象为此)

最后在需要找代理的类里面进行相应方法的调用

demo下载地址:http://download.csdn.net/detail/zhuangjingweijojo/5215381


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值