很多情況下,我們需要將其它控件產(chǎn)生的window 隱藏,這幾天做項(xiàng)目的時(shí)候發(fā)現(xiàn)肆资,當(dāng)自己打開一個(gè)帶有winodw的控件,然后收到一下?lián)尩窍⒃钪ィ约旱腶pp回到了首頁(yè)迅耘,但是這個(gè)window還在,因此需要隱藏它监署。
注意點(diǎn)
- UIAlertView 與 UIActionSheet無法從UIApplication.sharedApplication.windows取得。
- 既然要隱藏window 級(jí)別是Normal的自然不能隱藏纽哥。
方案
為了全局取到 UIAlertView 和 UIActionSheet Hook它們的show方法钠乏。或者直接用方法替換的方式春塌,將自定義方法與show方法替換晓避,起到存儲(chǔ)的作用。
做個(gè)判斷即可只壳。
實(shí)現(xiàn)
我這里因?yàn)楣こ汤镆呀?jīng)集成了Aspects所以就用hook的方式
UIActionSheet
+ (void)load
{
id sheetShowInViewHook = ^(id<AspectInfo> aspectInfo) {
if ([aspectInfo.instance isKindOfClass:[UIActionSheet class]]){
UIActionSheet *sheet = aspectInfo.instance;
[UIWindow saveAlertOrSheetView:sheet];
}
};
[self aspect_hookSelector:@selector(showInView:)
withOptions:AspectPositionAfter
usingBlock:sheetShowInViewHook
error:nil];
}
UIAlertView
+ (void)load
{
id alertShowHook = ^(id<AspectInfo> aspectInfo) {
if ([aspectInfo.instance isKindOfClass:[UIAlertView class]]){
UIAlertView *alertView = aspectInfo.instance;
[UIWindow saveAlertOrSheetView:alertView];
}
};
[self aspect_hookSelector:@selector(show)
withOptions:AspectPositionAfter
usingBlock:alertShowHook
error:nil];
}
為了使用方便俏拱,就直接給window定一個(gè)分類
==這里用NSHashTable 防止重復(fù)儲(chǔ)存==
static NSHashTable *viewTable;
+ (void)load
{
viewTable = [NSHashTable weakObjectsHashTable];
}
+ (void)saveAlertOrSheetView:(UIView *)view
{
[viewTable addObject:view];
}
+ (void)hideAllWindowsExceptNormal
{
for (UIWindow *window in UIApplication.sharedApplication.windows) {
BOOL windowLevelNormal = (window.windowLevel != UIWindowLevelNormal);
if(windowLevelNormal) {
[window setHidden:YES];
}
}
for (UIView *view in viewTable) {
if ([view isKindOfClass:[UIAlertView class]]) {
UIAlertView *alertView = view;
[alertView dismissWithClickedButtonIndex:alertView.cancelButtonIndex animated:NO];
}
if ([view isKindOfClass:[UIActionSheet class]]) {
UIActionSheet *acitonSheet = view;
[acitonSheet dismissWithClickedButtonIndex:acitonSheet.cancelButtonIndex animated:NO];
}
}
}