Swift UI - 告警框(UIAlertView)

注:代码已升级至Swift4

创建告警框

创建并弹出一个告警框,并带有“确定”和“取消”两个按钮

注:自iOS 8起,建议使用UIAlertController。点击查看UIAlertController的用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

let alertView = UIAlertView()
alertView.title = "系统提示"
alertView.message = "您确定要离开appblog.cn吗?"
alertView.addButtonWithTitle("取消")
alertView.addButtonWithTitle("确定")
alertView.cancelButtonIndex = 0
alertView.delegate = self;
alertView.show()
}

func alertView(alertView:UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if (buttonIndex == alertView.cancelButtonIndex) {
print("点击了取消")
} else {
print("点击了确认")
}
}
}

告警框样式

告警框有下面4种样式

1
2
3
4
Default:默认样式
PlainTextInput:带输入框的告警框
SecureTextInput:带密码框的告警框
LoginAndPasswordInput:带输入框和密码框的告警框

下面是一个使用输入框和密码框的告警框样例:

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
import UIKit

class ViewController: UIViewController {

var alertView = UIAlertView()

override func viewDidLoad() {
super.viewDidLoad()

alertView.title = "系统登录"
alertView.message = "请输入用户名和密码!"
alertView.addButtonWithTitle("取消")
alertView.addButtonWithTitle("确定")
alertView.cancelButtonIndex = 0
alertView.delegate = self;
alertView.alertViewStyle = UIAlertViewStyle.LoginAndPasswordInput
alertView.show()
}

func alertView(alertView:UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if (buttonIndex == alertView.cancelButtonIndex) {
print("点击了取消")
} else {
let name = alertView.textFieldAtIndex(0)
let password = alertView.textFieldAtIndex(1)
print("用户名是:\(name!.text) 密码是:\(password!.text)")
}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :