swift密码输入弹窗

首先附上链接:https://github.com/wangtaoHappy/SwiftPassword
在此 demo中主要涉及到的知识点有一下几个:
1:swift中协议的写法和使用
声明协议,继承自NSObjectProtocol

protocol PasswordAlertViewDelegate:NSObjectProtocol{
    func passwordCompleteInAlertView(alertView:PasswordAlertView, password:NSString)
}

设定属性

weak var delegate:PasswordAlertViewDelegate?

将想要得到的值传递出去

func sure(sender:UIButton) {
        print("确定")
        delegate?.passwordCompleteInAlertView(alertView:self, password: self.textFiled.text! as NSString)
    }

遵守协议

class ViewController: UIViewController,PasswordAlertViewDelegate

在UIController中的调用

func inputPassword() {
        let pswAlertView = PasswordAlertView.init(frame: self.view.bounds)
        pswAlertView.delegate = self
        self.view.addSubview(pswAlertView)
    }
   

    func passwordCompleteInAlertView(alertView: PasswordAlertView, password: NSString) {
        alertView.removeFromSuperview()
        print("password:",password);
        self.label.text = NSString.init(format: "密码:\(password)" as NSString) as String
    }

2:键盘的出现和隐藏的监听,以及view随键盘高度变化而变化
键盘监听

NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillShow(Info:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardWillHide(Info:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

得到信息后,根据键盘高度设置弹窗的高度

func keyBoardWillShow(Info:NSNotification) {
        let userInfos = Info.userInfo![UIKeyboardFrameEndUserInfoKey]
        
        let heigh = ((userInfos as AnyObject).cgRectValue.size.height)
        
        self.BGView.center = CGPoint.init(x: self.BGView.center.x , y:ScreenH - heigh - self.BGView.frame.size.height/2 - 10)
    }
    
    func keyBoardWillHide(Info:NSNotification) {
        self.BGView.center = self.center
    }

3:textFiled的使用方法

let textFiled = UITextField.init(frame: CGRect.init(x: 0, y: Int(line.frame.origin.y) + 30, width: Int(bgViewW), height: borderH))
        textFiled.backgroundColor = UIColor.clear
        //设置代理
        textFiled.delegate = self
        //监听编辑状态的变化
        textFiled.addTarget(self, action: #selector(textFiledValueChanged(textFiled:)), for: .editingChanged)
        textFiled.tintColor = UIColor.clear
        textFiled.textColor = UIColor.clear
        textFiled.becomeFirstResponder()
        //设置键盘类型为数字键盘
        textFiled.keyboardType = .numberPad
        self.textFiled = textFiled;
        bgView.addSubview(self.textFiled)

textFiled 代理方法的使用

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if string.characters.count == 0 {//判断是是否为删除键
            return true
        }else if (textField.text?.characters.count)! >= pointCount {
            //当输入的密码大于等于6位后就忽略
            return false
        } else {
            return true
        }
    }

每天努力一点点!!!

你可能感兴趣的:(swift密码输入弹窗)