听起来您实际上是在尝试在 iOS 上重新创建“Toast”。好消息,已经有人这样做了。看到这个项目。
编辑:不想使用 iToast。我喜欢你的风格,代码少。这是我想出的。正如其他人所说,克服模态特性的唯一方法似乎很明显,UIAlertView
就是添加一个超级视图来处理触摸事件。但是您不必每次都手动执行此操作,请考虑 subclassing UIAlertView
。尝试这样的事情:
编辑: @wagashi,感谢您接受我的回答,并感谢您提醒我这setFrame:
是一个调整大小的好地方。您的代码确实发出了一个非常类似于吐司的小警报,但是当我尝试它时,我发现如果消息太长,视图似乎会崩溃。所以我已经修改setFrame:
为简单地将警报的大小减小大约一个按钮的大小,并保持在屏幕的中心。这样该课程才能准确地回答问题标题“iOS 如何在任何地方一键关闭 UIAlertView?”
NoButtonAlertView.h
#import <UIKit/UIKit.h>
@interface _NoButtonAlertViewCover : UIView
@property (nonatomic,assign) UIAlertView *delegate;
@end
@interface NoButtonAlertView : UIAlertView
-(id)initWithTitle:(NSString *)title message:(NSString *)message;
@end
NoButtonAlertView.m
#import "NoButtonAlertView.h"
@implementation _NoButtonAlertViewCover
@synthesize delegate = _delegate;
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
[self removeFromSuperview];
[_delegate dismissWithClickedButtonIndex:0 animated:YES];
}
@end
@implementation NoButtonAlertView
-(void)show{
[super show];
_NoButtonAlertViewCover *cover = [[_NoButtonAlertViewCover alloc] initWithFrame:[UIScreen mainScreen].bounds];
cover.userInteractionEnabled = YES;
cover.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:.01];
cover.delegate = self;
[self.superview addSubview:cover];
}
-(id)initWithTitle:(NSString *)title message:(NSString *)message{
if ((self = [super initWithTitle:title message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil])){
}
return self;
}
- (void)setFrame:(CGRect)rect {
// Called multiple times, 4 of those times count, so to reduce height by 40
rect.size.height -= 10;
self.center = self.superview.center;
[super setFrame:rect];
}
@end
使用这个简单UIAlertView
的子类及其UIView
作为封面的子类,您可以像使用标准UIAlertView
. 像这样:
NoButtonAlertView *alert = [[NoButtonAlertView alloc] initWithTitle:@"Hello" message:@"I am the very model of a modern major general; I'm information, vegitable, animal, and mineral."];
[alert show];
将产生:
![自定义警报视图](https://i.stack.imgur.com/R5OTG.png)