Let’s use the code to monitor keyboard pop-up/hide:
- (void)viewDidLoad {
// 获取通知对象
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
/*
注册监听,
1>Observer参数:是哪个对象要监听
2>selector参数:监听的对象收到通知后执行哪个方法
3>name参数:监听通知的名称,明确监听哪个类型名称的通知,可以自定义通知名称。(如果不写,则会监听发出通知对象的所有通知)
4>object参数:明确发出通知的对象.(如果不写,则会根据通知名称来监听)
5>如果不写4.5参数,则会监听所有通知
*/
[center addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
/*
发送通知
1>Name参数:发送的通知名称
2>object参数:发出通知的主体
3>userinfo参数:发出通知的内容信息,为NSDictionary类型
*/
[center postNotificationName:UIKeyboardDidChangeFrameNotification object:self userInfo:@{}];
}
// 收到通知后执行的方法
-(void)keyboardWillChange:(NSNotification *)notification{
// 获取键盘改变通知中的userinfo CGRect
CGRect rectEnd = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// 从CGRect中获取Y将要移动到的位置
CGFloat keyboardY = rectEnd.origin.y;
// 根据键盘Y即将移动到的位置,计算出view的偏移量
CGFloat tranformValue = keyboardY - ScreenHeight;
// 设置view的transform
self.view.transform = CGAffineTransformMakeTranslation(0, tranformValue);
}
Examples of commonly used notification codes for monitoring device status:
// 设备改变旋转方向的通知
UIDeviceOrientationDidChangeNotification;
// 设备电池状态改变的通知
UIDeviceBatteryStateDidChangeNotification;
// 设备电池电量改变的通知
UIDeviceBatteryLevelDidChangeNotification;
// 近距离传感器通知(例如贴近耳朵)
UIDeviceProximityStateDidChangeNotification;
// 通知示例
UIDevice *device = [UIDevice currentDevice];
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(address) name:UIDeviceOrientationDidChangeNotification object:device];
What notifications and agents have in common:
Notifications and proxies can both complete communication between objects (the A object tells the B object what happened, and at the same time passes certain parameters to the B object)
The difference between notifications and agents:
Agents are a one-to-one relationship (one object can only notify one object of what happened)
Notifications can have a one-to-many relationship (one notification can be sent to multiple notification recipients)