ios页面数据传输方法使用,代理,block返回,广播通知

151 阅读1分钟

1代理。

//在需要传值的.h文件定义代理
@protocol PerfectInfoViewDelegate <NSObject>
-(void)didSureClick:(NSDictionary*)dic;
@end
@interface PerfectInfoView : UIView
@property (nonatomic, unsafe_unretained) id <PerfectInfoViewDelegate> delegate;
@end

//.m声明
@synthesize delegate;

[delegate didSureClick:@{}];//在对应的点击方法中传值

//主页面使用时直接调用
-(void)didSureClick:(NSDictionary *)dic{

}

2.block值返回。

//在需要传值的.h文件中声明block
@property (copy, nonatomic) void(^changeDataBlock)(NSDictionary*dic);

//在传值的.m文件中使用block
if (self.changeDataBlock) 
{
   self.changeDataBlock(@{});
}

//主页面使用
[vc setChangeDataBlock:^(NSDictionary * _Nonnull dic) {
          //"获取修改后的值为==%@",dic);   
}];   //vc 为传值视图

3.block方法返回

+(void)showActionSheetView:(NSDictionary*)dic atViewController:(UIViewController *)vc with:(void(^)(int index))block;




+(void)showActionSheetView:(NSDictionary*)dic atViewController:(UIViewController *)vc with:(void(^)(int index))block{
    NSString * title=dic[@"title"];
    NSString * cancelButton=dic[@"cancelButton"];
    NSArray * arr=dic[@"otherButtons"];
    if ([title isEmptyString]) {
        title=nil;
    }
    UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    if (!IS_IPHONE) {
       UIPopoverPresentationController *popController = [actionSheet popoverPresentationController];
             popController.sourceRect = CGRectMake(SCREEN_WIDTH/2.0-LWidth(100),SCREEN_HEIGHT,LWidth(200), LWidth(200));
             popController.sourceView = vc.view;
             popController.permittedArrowDirections = UIPopoverArrowDirectionAny;
    }
    for (int i=0; i<arr.count; i++) {
        NSString * message=[NSString stringWithFormat:@"%@",arr[i]];
        UIAlertAction *action = [UIAlertAction actionWithTitle:message style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            block(i);
            
        }];
        [actionSheet addAction:action];
    }
    UIAlertAction *action4 = [UIAlertAction actionWithTitle:cancelButton style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            block(-1);
        }];
        [actionSheet addAction:action4];
        actionSheet.modalPresentationStyle=UIModalPresentationFullScreen;
        [vc presentViewController:actionSheet animated:YES completion:nil];
       
        
}

4.广播通知

//发送广播
[[NSNotificationCenter defaultCenter]postNotificationName:@"getNotificationMessage"
                    object:nil userInfo:userInfo];

//注册广播并做收到广播通知的方法
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getMessage:) name:@"getNotificationMessage" object:nil];

//收到广播通知处理
-(void)getMessage:(NSNotification *)aNotification{

}

//当我们不使用时,删除广播通知
[[NSNotificationCenter defaultCenter]removeObserver:self name:@"getNotificationMessage" object:nil];

\