轉(zhuǎn)載:swift.gg
作者:Arthur Knopper廊佩,原文鏈接链烈,原文日期:2015-12-21譯者:pmst援奢;校對:Cee憎茂;定稿:千葉知風(fēng)
創(chuàng)建可以彈出Alert Controller的Button
Paste_Image.png
這個(gè)Button叫“Log in”珍语,autolayout布局就省略了。
連接Button和viewController
Paste_Image.png
代碼實(shí)現(xiàn)
@IBAction func login(sender: AnyObject) {
//1.申明兩個(gè)textField
var usernameTextField: UITextField?
var passwordTextField: UITextField?
//2. 創(chuàng)建一個(gè)alertController
let alertController = UIAlertController(title: "log in", message: "please enter your credentials", preferredStyle: UIAlertControllerStyle.Alert)
//3. 創(chuàng)建一個(gè)在alertController的按鈕竖幔,用來打印輸入的username和password
let loginAction = UIAlertAction(title: "log in", style: UIAlertActionStyle.Default) { (action) -> Void in
if let username = usernameTextField?.text {
print("username = \(username)")
} else {
print("no name entered")
}
if let password = passwordTextField?.text {
print("password = \(password)")
} else {
print("No password entered")
}
}
//4. 給alertController添加usernameTextField
alertController.addTextFieldWithConfigurationHandler { (txtUsername) -> Void in
usernameTextField = txtUsername
usernameTextField!.placeholder = "<Your username here>"
}
//5. 給alertController添加usernameTextField
alertController.addTextFieldWithConfigurationHandler { (txtPassword) -> Void in
passwordTextField = txtPassword
passwordTextField!.secureTextEntry = true
passwordTextField!.placeholder = "<your password here>"
}
//6. 給alertController添加按鈕的action
alertController.addAction(loginAction)
//7. 彈出alertController
self.presentViewController(alertController, animated: true, completion: nil)
}
結(jié)果展示
Paste_Image.png