iOS NSNotification通知的使用介绍

以监听键盘弹出/隐藏代码来说明:

- (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);
}

常用监听设备状态的通知代码示例:

    // 设备改变旋转方向的通知
    UIDeviceOrientationDidChangeNotification;
    
    // 设备电池状态改变的通知
    UIDeviceBatteryStateDidChangeNotification;
    
    // 设备电池电量改变的通知
    UIDeviceBatteryLevelDidChangeNotification;
    
    // 近距离传感器通知(例如贴近耳朵)
    UIDeviceProximityStateDidChangeNotification;
    
    // 通知示例
    UIDevice *device = [UIDevice currentDevice];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(address) name:UIDeviceOrientationDidChangeNotification object:device];

通知和代理的共同点:

通知和代理,都能完成对象之间的通信(A对象告诉B对象发生了什么事,同时传递某些参数给B对象)

通知和代理的不同点:

代理是一对一的关系(1个对象只能通知1个对象发生了什么事)

通知可以一对多的关系(1个通知可以发送给多个通知接受对象)

猜你喜欢

转载自blog.csdn.net/JustinZYP/article/details/124424192