iOS 弹窗alertView使用详解

转自:http://blog.it985.com/4321.html

alertView是iOS自带的弹窗通知框,我们来看下默认样式的效果图
屏幕快照 2012-01-01 上午8.11.33
下面直接上代码

1
2
3
4
5
- (void)delete{
//弹窗
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"是否删除?" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
[alertView show];
}

如果想做成下面只有一个按钮的
屏幕快照 2014-12-05 上午8.39.35

1
2
3
4
5
- (void)delete{
//弹窗
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"是否删除?" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alertView show];
}

弹窗后点击确定或者取消按钮想要加点事件的话可以这样

1
2
3
4
5
6
7
8
9
10
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex//点击弹窗按钮后
{
    NSLog(@"buttonIndex:%ld",(long)buttonIndex);
 
    if (buttonIndex == 0) {//取消
        NSLog(@"取消");
    }else if (buttonIndex == 1){//确定
        NSLog(@"确定");
    }
}

最左边的按钮的buttonIndex是0,右边的按钮buttonIndex依次加一。

现在来说一下自定义样式的用法,alertView不但可以做出只有文字样式的弹窗,也可以做出图片样式或者带有pickerView的弹窗,现在来说一下带有可编辑文本框弹窗的做法
先看一下效果图
屏幕快照 2014-12-05 上午9.05.42
使用之前先引入库
没有库的请先下载库
CustomIOS7AlertView

1
#import "CustomIOS7AlertView.h"

直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
- (void)alertViewUser
{
    CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init];
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"上一个", @"确定", @"下一个", nil]];
 
    UIView *demoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 290, 120)];
 
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 180, 20)];
    title.text = @"请填写姓名";
    [demoView addSubview:title];
 
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 50, 270, 30)];
    textField.backgroundColor = [UIColor whiteColor];
    textField.returnKeyType = UIReturnKeyDone;
    textField.delegate = self;
    [demoView addSubview:textField];
 
    [alertView setContainerView:demoView];//把demoView添加到自定义的alertView中
 
    //这里是点击按钮之后触发的事件
    [alertView setOnButtonTouchUpInside:^(CustomIOS7AlertView *alertView, int buttonIndex) {
        if (buttonIndex==0) {//上一个
            NSLog(@"上一个");
        } else if (buttonIndex==1) {//确定
            NSLog(@"确定");
            NSLog(@"texeValue:%@",textField.text);
        } else if (buttonIndex == 2){//先保存数据,然后跳到下一个
            NSLog(@"下一个");
        }
 
    }];
 
    [alertView show];
 
}

要注意的是把demoView添加到alertView的方法是“[alertView setContainerView:demoView];”
并且点击alertView触发的事件也在上面的注释中标出。可直接把代码贴过去使用。
如果想添加图片或者其他的可以直接在demoView里面添加。控制好尺寸就可以了。

本文永久地址:http://blog.it985.com/4321.html
本文出自 IT985博客 ,转载时请注明出处及相应链接。

原文地址:https://www.cnblogs.com/feiyu-mdm/p/5566581.html