转载:swift.gg
作者:Arthur Knopper,原文链接,原文日期:2015-12-21译者:pmst;校对:Cee;定稿:千叶知风
创建可以弹出Alert Controller的Button
Paste_Image.png这个Button叫“Log in”,autolayout布局就省略了。
连接Button和viewController
Paste_Image.png代码实现
@IBAction func login(sender: AnyObject) {
//1.申明两个textField
var usernameTextField: UITextField?
var passwordTextField: UITextField?
//2. 创建一个alertController
let alertController = UIAlertController(title: "log in", message: "please enter your credentials", preferredStyle: UIAlertControllerStyle.Alert)
//3. 创建一个在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)
}
网友评论