UIAlertView关联属性 + 分类

UIAlertView关联属性

#import "FirstViewController.h"
//#import "UIAlertView+TmfUIAlertView.h"
#import <objc/runtime.h>
static const void *alertBlock = "alertBlock";
@interface FirstViewController ()

@end
@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"s" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:@"?", nil];
    void(^block)(NSInteger) = ^(NSInteger btnIndex) {  
        NSLog(@"btnIndex:%ld",(long)btnIndex);
    };    
    objc_setAssociatedObject(self, alertBlock, block, OBJC_ASSOCIATION_COPY);
//    alert.block = ^(UIAlertView *alertView) {
//        
//        NSLog(@"ssss:%@",alertView);
//        
//    };
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex NS_DEPRECATED_IOS(2_0, 9_0);
{
    void(^block)(NSInteger) = objc_getAssociatedObject(self, alertBlock);
    block(buttonIndex);
}
@end

UIAlertView 分类 增加block属性

#import <UIKit/UIKit.h>
typedef void(^alertViewBlock)(UIAlertView *);
@interface UIAlertView (TmfUIAlertView)<UIAlertViewDelegate>
@property(nonatomic, copy) alertViewBlock block;
@end
#import "UIAlertView+TmfUIAlertView.h"
#import <objc/runtime.h>
static const void *tmfAlertViewKey = "tmfAlertViewKey";
@implementation UIAlertView (TmfUIAlertView)
- (void)setBlock:(alertViewBlock) block{
    objc_setAssociatedObject(self, tmfAlertViewKey, block, OBJC_ASSOCIATION_COPY);
    self.delegate = self;  
}
- (alertViewBlock)block{
    return objc_getAssociatedObject(self, tmfAlertViewKey);  
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex NS_DEPRECATED_IOS(2_0, 9_0);
{
    self.block(alertView);  
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容