1.Notification
通知是iOS开发中常用的一种传值响应方法,NSNotification采用的单例设计模式,当给通知中心注册一个key以后,那么无论在什么地方只要给通知中心发送一个这个key的消息,那么就实现了通信传值,注册的通知的对象就会调用相应的方法。 因此,通知是一对多的。
如我有一个controller,controller内部有两个view,view1和view2,需要在点击view1上按钮的时候,去改变view2的颜色。则先需要将controller添加为观察者,并实现notiChangeColor方法,代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
randomView*view1= [self.viewviewWithTag:101];
self.colorView= view1;
//添加观察者接受通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiChangeColor) name:@"changeColor" object:nil];
}
#pragma mark -NSNotificationCenter
-(void)notiChangeColor{
NSLog(@"NSNotification");
UIView*view2 = [self.viewviewWithTag:102];
view2.backgroundColor = randomColor;
}
此时,我们只需要在randomView中绑定btn的点击事件,然后发送通知,观察者就能够收到通知,去调用通知绑定的方法,需要注意的是发送和接收方的NotificationName一定要相同,object可以传递参数
- (IBAction)notificationChangeColor:(id)sender {
//NSNotificationCenter,发送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"changeColor" object:nil];
}
2.Delegate
代理几乎是iOS开发中最常用的传值方式,在项目中的AppDelegate就是使用的这种设计模式,不仅如此,还有很多原生的控件也使用的这种设计模式,比如:UITextFiled,UITableView等等。
上面的情景中,如使用delegate实现的话,首先需要在randomView这个类中定义一个协议,并新增一个协议属性(修饰要用一般使用assign,防止循环引用,同时遵循定义的协议),话不多说,上代码。
@protocol colorDelegate <NSObject>
-(void)delegateChangeColor;
@end
@interface randomView :UIView
@property(nonatomic,assign) id<colorDelegate> delegate;
@end
在randomView.m文件中,实现代理
- (IBAction)delegateChangeColor:(id)sender {
//delegate
if(self.delegate) {
[self.delegate delegateChangeColor];
}
}
在ViewController中,只需要绑定randomView的代理为这个控制器,同时控制器也要遵循colorDelegate这个协议方法
@interface ViewController ()<colorDelegate>
@property(nonatomic,weak)randomView *colorView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
randomView*view1= [self.viewviewWithTag:101];
self.colorView= view1;
view1.delegate=self;
}
最后在viewcontroller中实现colorDelegate
#pragma mark -colorDelegate
-(void)delegateChangeColor{
NSLog(@"Delegate");
UIView*view2 = [self.viewviewWithTag:102];
view2.backgroundColor = randomColor;
}
3.Block
相比于上面两种通讯模式,block在我们平时开发的时候是使用最频繁的,因为它使用起来最简单。
上面的场景中,如果使用block来实现的话,我们只需要在randomView.h中新增一个block属性(copy修饰),第一个void代表返回参数,第二个void代表传入参数。
@property(nonatomic,copy) void (^changeColor)(void);
在randomView.m文件中调用
- (IBAction)blockChangeColor:(id)sender {
if (self.changeColor) {
self.changeColor();
}
}
最后在viewcontroller中实现
- (void)viewDidLoad {
[super viewDidLoad];
randomView*view1= [self.view viewWithTag:101];
self.colorView= view1;
view1.delegate=self;
view1.changeColor= ^{
UIView*view2 = [self.view viewWithTag:102];
view2.backgroundColor=randomColor;
};
}
希望对您有帮助,如果文章中有问题,欢迎评论留言,谢谢支持欢迎关注,我会在空余时间更新技术文章~