问题:接手了一个项目没多久,今天测试提交了一个bug,算是逻辑上的bug吧。前台收到了mqtt发送过来的一个消息,然后用UIAlertView显示了一个弹框,上面有接受和拒绝两个按钮可以选择。也就是说,用户在某一个页面进行着某一项操作突然弹出了一个提示框,并且我必须选其一。但是如果用户不想现在决定,就需要隐藏这个弹窗,此时并没有取消按钮,所以就产生了一个需求:点击UIAlertView的黑色背景隐藏弹窗。
之前的代码这样的:
UIAlertView *organizationAlert = [[UIAlertView alloc]initWithTitle:nil
message:[NSString stringWithFormat:@"尊敬的用户,您的平台账号被%@邀请加入,请确认。",notifica.object]
delegate:self
cancelButtonTitle:@"拒接"
otherButtonTitles:@"加入", nil];
[kUserDefaults setObject:[NSString stringWithFormat:@"尊敬的用户,您的平台账号被%@邀请加入,请确认。",notifica.object] forKey:@"NotificaObject"];
[self.organizationAlert show];
现在我想添加一个点击事件,然后在事件里面去dismiss弹窗。这个时候需要把organizationAlert写成属性。问题来了:这一切都是写在类目里面的!
#import "AppDelegate.h"
@interface AppDelegate (Notifies)
@end
明白了吧,在这里添加属性,就需要用到runtime了,这也是runtime需要用的为数不多的应用场景:添加属性。
下面直接放完整代码:
①把弹窗写成属性
#import "AppDelegate.h"@interface AppDelegate (Notifies)
@property (nonatomic, strong) UIAlertView *organizationAlert;
@end
②添加getter setter方法
//strKey 唯一标识
static void *strKey = &strKey;
- (void)setOrganizationAlert:(UIAlertView *)organizationAlert{
objc_setAssociatedObject(self, &strKey, organizationAlert, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (UIAlertView *)organizationAlert{
return objc_getAssociatedObject(self, &strKey);
}
③使用
#pragma mark -- 组织邀请
-(void)organizationInvite:(NSNotification *)notifica{
self.organizationAlert = [[UIAlertView alloc]initWithTitle:nil
message:[NSString stringWithFormat:@"尊敬的用户,您的平台账号被%@邀请加入,请确认。",notifica.object]
delegate:self
cancelButtonTitle:@"拒接"
otherButtonTitles:@"加入", nil];
[kUserDefaults setObject:[NSString stringWithFormat:@"尊敬的用户,您的平台账号被%@邀请加入,请确认。",notifica.object] forKey:@"NotificaObject"];
[self.organizationAlert show];
//点击背景隐藏
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
tap.numberOfTapsRequired = 1;
tap.cancelsTouchesInView = NO;
[[UIApplication sharedApplication].keyWindow addGestureRecognizer:tap];
}
//点击事件处理
- (void)tap:(UITapGestureRecognizer *)tap
{
if (tap.state == UIGestureRecognizerStateEnded){//下面代码自己去理解
CGPoint location = [tap locationInView:nil];
if (![self.organizationAlert pointInside:[self.organizationAlert convertPoint:location fromView:self.organizationAlert.window] withEvent:nil]){
[self.organizationAlert.window removeGestureRecognizer:tap];
[self.organizationAlert dismissWithClickedButtonIndex:0 animated:YES];
}
}
}
网友评论