一.通知传值 NSNotification
//获取通知中心
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//制作一个通知
NSNotification *notifi = [[NSNotification alloc]initWithName:@"showtext" object:nil userInfo:nil];
//发送通知
[center postNotification:notifi];
//第二种方式,给一个通知名字和携带对象,通知中心自动创建一个通知,并发送出去
[center postNotificationName:@"showtext" object:textField.text];
//捕获通知
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(showText:) name:@"showtext" object:nil];
-(void)showText:(NSNotification *)notify
{
UILabel *label = (id)[self.view viewWithTag:10];
//获取通知携带的对象
NSString *text = notify.object;
label.text = text;
}
二. block传值
1.声明一个block变量
@property(nonatomic, copy) UIColor * (^showText)(NSString * text);
2.实现block
UIColor *(^myblock)(NSString * text) = ^(NSString *text){
//在代码块中实现功能
label.text = text;
return [UIColor redColor];
};
UIColor *(^myblock)(NSString * text) = ^(NSString *text){
//在代码块中实现功能
label.text = text;
return [UIColor redColor];
};
3.调用block
if(_showText){
//3调用block
UIColor *color = _showText(textField.text);
self.view.backgroundColor = color;
}
三.代理传值 delegate
1.声明协议
1.驱动方声明协议《规定实现什么方法》,驱动方声明一个遵循协议的属性
@protocol ShowTextDelegate <NSObject>
@required
- (void)showText:(NSString *)text;
@optional
- (UIColor *) showTextReturnColor:(NSString *)text;
@end
// 2.代理方,要遵循协议,实现协议方法(让代理方知道它要做什么)
@interface RootViewController ()<ShowTextDelegate>
-(void)showText:(NSString *)text
{
UILabel *label = (id)[self.view viewWithTag:10];
label.text = text;
}
//3.建立代理关系
svc.delegate = self;
//4. 驱动方驱动代理方法执行协议
if (_delegate && [_delegate respondsToSelector:@selector(showTextReturnColor:)]) {
UIColor *color = [_delegate showTextReturnColor:textField.text];
self.view.backgroundColor = color;
}
网友评论