只要將UIAlertViewStyle屬性設定為LoginAndPasswordInput,
對話方塊中就會同時提供PlainTextInpu以及一個SecureTextInput。
使用textFieldAtIndex(index)方法,可以取得UITextField型別的文字方塊。
畫面如下
設定Button事件與連結
設定Label連結
程式碼
// // ViewController.swift // book // // Created by boywhy chen on 2016/12/25. // Copyright © 2016年 boywhy chen. All rights reserved. // import UIKit class ViewController: UIViewController,UIAlertViewDelegate { @IBOutlet weak var mLabel: UILabel! @IBOutlet weak var mButton: UIButton! //來個一組帳密 let UserName:String = "boywhy" let Password:String = "1234" override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //心情好,用個圓角按鈕 mButton.layer.backgroundColor = UIColor.brownColor().CGColor mButton.layer.cornerRadius = 15 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func showAlertView(sender: AnyObject) { //create UIAlertView var alertView:UIAlertView = UIAlertView() alertView.title = "登入" alertView.message = "Welcome" alertView.delegate = self alertView.addButtonWithTitle("取消") alertView.addButtonWithTitle("登入") //Set Style to Login And Password alertView.alertViewStyle = UIAlertViewStyle.LoginAndPasswordInput alertView.show() } //處理函式名字固定是alertView func alertView(alertView:UIAlertView!,clickedButtonAtIndex buttonIndex:Int) { switch(buttonIndex) { case 0: //cancel button break case 1://login button var textUserName:UITextField = alertView.textFieldAtIndex(0)! var textPassword:UITextField = alertView.textFieldAtIndex(1)! if(textUserName.text == UserName && textPassword.text == Password) { mLabel.text = "Welcom \(textUserName.text!)" } else { mLabel.text = "login fail" } break default: mLabel.text = "error" } } }
執行畫面
輸入正確帳密
輸入錯誤帳密
Swift比較特別的一點是字串的比較可以直接用== ,
和Java或C#不一樣,==只是比記憶體位置。
沒有留言:
張貼留言