您的位置:首页 > 产品设计 > UI/UE

IOS学习笔记--利用UIWindow实现自定义AlertView

2015-01-10 10:56 633 查看
最近项目开发,要做一个文件下载功能,本来想通过UIAlertView在下载过程中屏幕展示下载进度,但是在将UIProgressView作为子视图添加到UIAlertView时,一直看不到进度条,在网上搜了搜资料,原来时IOS7的UIAlertView不再支持通过[obj addSubView:obj]的方式。于是决定还是自己自定义一个AlertView,可以顺便学习一下。不过并不是说IOS7的UIAlertView不能加进度条,其实可以通过[obj:
setValue:obj : forKey@"accessoryView"]来实现。

三种实现方法:

1.setValue:obj  forKey:@"accessoryView" 

2.自定义

3.使用第三方库

1、依然使用UIAlertView展示

示例中只是在单一ViewController中的viewDidLoad方法内,生成一个UIAlertView实例,利用[alertView setValue:(id) forKey:@"accessoryView"]实现添加其他view。

代码如下:

@implementation ESViewController

- (void)viewDidLoad
{
[super viewDidLoad];

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Title"
message:@"message"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];

UIProgressView *progressView = [[UIProgressView alloc]
initWithProgressViewStyle:UIProgressViewStyleBar];
progressView.progress = 0.5f;

[alertView setValue:progressView forKey:@"accessoryView"];

[alertView show];
}


界面效果:



2、使用UIWindow自定义

此类方法网上有很多资料,即通过自定义一个继承自UIWindow的类,来实现自定义AlertView样式,可以更加自由的展示自己想添加的内容,这里以添加UIProgressView为例,实现一个简单的AlertView样式。

创建一个新的UIWindow,并将此UIWindow的级别定义为UIWindowAlertLevel,则当前Window将会占据屏幕进行展示。需要实现的内容主要有:1、定义要展示的view2、实现show方法3、实现dismiss方法

代码如下:

@interface ESAlertView : UIWindow

- (void)show;
- (void)dismiss;

@end

@implementation ESAlertView

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.windowLevel = UIWindowLevelAlert;
self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.25];

UIView *view = [[UIView alloc]
initWithFrame:CGRectMake(60, 160, 200, 100)];
view.backgroundColor = [UIColor whiteColor];

UILabel *label = [[UILabel alloc]
initWithFrame:CGRectMake(60, 20, 80, 20)];
label.text = @"message";

UIProgressView *progressView = [[UIProgressView alloc]
initWithProgressViewStyle:UIProgressViewStyleBar];
progressView.frame = CGRectMake(20, 60, 160, 10);
progressView.progress = 0.5f;

UIButton *button = [[UIButton alloc]
initWithFrame:CGRectMake(80, 70, 40, 20)];
button.backgroundColor = [UIColor yellowColor];
[button setTitle:@"OK" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
[button addTarget:self
action:@selector(dismiss)forControlEvents:UIControlEventTouchDown];

[view addSubview:label];
[view addSubview:progressView];
[view addSubview:button];
[self addSubview:view];
}

return self;
}

- (void)show
{
[self makeKeyAndVisible];
}

- (void)dismiss
{
self.hidden = YES;
[self resignKeyWindow];
[self release];
}
此处要dismiss方法的self.hidden = YES,测试时,如果不通过设置hidden属性,在通过button点击时,必须点击两次AlertView才会消失,此处还不太清楚问题所在,有待继续对UIWindow进行研究。

界面效果:



另外在查看iOS8的开发者library时,发现UIAlertView已经是deprecated的了,代替的为类UIAlertController

https://developer.apple.com/library/ios/documentation/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息