利用利用UIWindow自创UIAlert,实现界面的完全自定义。
创建类zAlert,继承于UIWindow:
@interface zAlert : UIWindow
{
UIWindow *_mainWindow;
}
- (void)show;
@end
- (id)init{
if (self = [super initWithFrame:[[UIScreen mainScreen] applicationFrame]]) {
UIColor *color = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]; //背景色,这里设置黑色,透明度0.5
self.backgroundColor = color;
self.windowLevel = UIWindowLevelAlert; //这里是window的响应等级,UIWindowLevelAlert > UIWindowLevelStatusBar > UIWindowLevelNormal
UIView *zView = [[UIView alloc]initWithFrame:CGRectMake(40, 220, 240, 160)]; //弹窗
UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; //确定按钮
button.frame=CGRectMake(90, 120, 60, 30);
[button setTitle:@"确定" forState:UIControlStateNormal];
[button addTarget:self action:@selector(remove) forControlEvents:UIControlEventTouchUpInside]; //点击可返回
[zView addSubview:button];
zView.backgroundColor = [UIColor blueColor]; //这里设置为蓝色
[self addSubview:zView];
_mainWindow = [UIApplication sharedApplication].delegate.window; //弹窗出现之前的window
}
return self;
}
/* 出现 */
- (void)show{
[_mainWindow resignKeyWindow];
[self makeKeyAndVisible];
[UIApplication sharedApplication].delegate.window = self;
}
/* 返回 */
- (void)remove{
[self removeFromSuperview];
[self resignKeyWindow];
[self resignKeyWindow];
[UIApplication sharedApplication].delegate.window = _mainWindow;
}
这样,自定义的alert控件就做好了。当然这里只是个简单的例子,可以开放些接口,控制button的生成,zView的自定义。下面来看看怎么使用。
在viewController 里:
zAlert *alert=[[zAlert alloc] init];
[alert show];
运行后,在屏幕中间就会弹出一个蓝色,底部有确定按钮的框,此时,不点击确定按钮,是不能做其他任何操作的,类似系统的UIAlert。