如何在Swift中切换UITextField安全文本条目(隐藏密码)?

时间:2016-06-17 04:25:36

标签: ios swift uitextfield

我目前有一个UITextfield,其中有一个眼睛图标,按下时应该打开和关闭安全文本条目。

secure text entry

我知道你可以勾选'#34;安全文字条目"属性检查器中的框但是如何执行它以便在按下图标时切换它?

26 个答案:

答案 0 :(得分:48)

使用此代码,

iconClick是bool变量,或者你需要其他条件检查它,

var iconClick = true

眼睛行动方法:

@IBAction func iconAction(sender: AnyObject) {
        if(iconClick == true) {
            passwordTF.secureTextEntry = false
        } else {
            passwordTF.secureTextEntry = true
        }

        iconClick = !iconClick
    }

希望它有用

答案 1 :(得分:34)

为什么要使用额外的var。在 eye 按钮的操作方法中,只需执行以下操作

password.secureTextEntry = !password.secureTextEntry

更新

Swift 4.2 (根据@ROC评论)

password.isSecureTextEntry.toggle()

答案 2 :(得分:30)

这种意外的副作用是,如果用户切换到不安全状态,然后返回以保护安全,则在用户继续输入时将清除现有文本。除非我们重置所选的文本范围,否则光标也可能会以错误的位置结束。

以下是处理这些案例的实现(Swift 4)

extension UITextField {
    func togglePasswordVisibility() {
        isSecureTextEntry = !isSecureTextEntry

        if let existingText = text, isSecureTextEntry {
            /* When toggling to secure text, all text will be purged if the user 
             continues typing unless we intervene. This is prevented by first 
             deleting the existing text and then recovering the original text. */
            deleteBackward()

            if let textRange = textRange(from: beginningOfDocument, to: endOfDocument) {
                replace(textRange, withText: existingText)
            }
        }

        /* Reset the selected text range since the cursor can end up in the wrong
         position after a toggle because the text might vary in width */
        if let existingSelectedTextRange = selectedTextRange {
            selectedTextRange = nil
            selectedTextRange = existingSelectedTextRange
        }
    }
}

此代码段正在使用replace(_:withText:)函数,因为它会触发.editingChanged事件,这恰好在我的应用程序中很有用。设置text = existingText也应该没问题。

答案 3 :(得分:16)

Swift 4 解决方案

对于简单切换isSecureTextEntry属性

,您不需要额外的if语句
func togglePasswordVisibility() {
        password.isSecureTextEntry = !password.isSecureTextEntry
    }

但是当您切换isSecureTextEntry时出现问题UITextField不会重新计算文本宽度,并且文本右侧有额外的空间。为避免这种情况,您应该以这种方式替换文本

func togglePasswordVisibility() {
        password.isSecureTextEntry = !password.isSecureTextEntry
        if let textRange = password.textRange(from: password.beginningOfDocument, to: password.endOfDocument) {
            password.replace(textRange, withText: password.text!)
        }
    }

<强>更新

Swift 4.2

而不是

password.isSecureTextEntry = !password.isSecureTextEntry

你可以这样做

password.isSecureTextEntry.toggle()

答案 4 :(得分:7)

使用UITextFiled右视图显示切换按钮

 var rightButton  = UIButton(type: .custom)
 rightButton.frame = CGRect(x:0, y:0, width:30, height:30)
 yourtextfield.rightViewMode = .always
 yourtextfield.rightView = rightButton

答案 5 :(得分:5)

目标c

设置RightButton的图像在viewdidload方法

[RightButton setImage:[UIImage imageNamed:@"iconEyesOpen"] forState:UIControlStateNormal];

    [RightButton setImage:[UIImage imageNamed:@"iconEyesClose"] forState:UIControlStateSelected];

然后为该RightButton设置动作方法

-(IBAction)RightButton:(id)sender
{

    if (_rightButton.selected)
    {

        _rightButton.selected = NO;

        _passwordText.secureTextEntry = YES;


        if (_passwordText.isFirstResponder) {
            [_passwordText resignFirstResponder];
            [_passwordText becomeFirstResponder];
        }
    }
    else
    {

      _rightButton.selected = YES;

        _passwordText.secureTextEntry = NO;

        if (_passwordText.isFirstResponder) {
            [_passwordText resignFirstResponder];
            [_passwordText becomeFirstResponder];
        }

    }
}

答案 6 :(得分:4)

我写了相同的扩展名。提供密码切换。

iOS password toggle eye icons

  1. 首先在资产中添加要切换的图像。

  2. 为UITextField添加以下扩展名。

    extension UITextField {
    fileprivate func setPasswordToggleImage(_ button: UIButton) {
        if(isSecureTextEntry){
            button.setImage(UIImage(named: "ic_password_visible"), for: .normal)
        }else{
            button.setImage(UIImage(named: "ic_password_invisible"), for: .normal)
    
        }
    }
    
    func enablePasswordToggle(){
        let button = UIButton(type: .custom)
        setPasswordToggleImage(button)
        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -16, bottom: 0, right: 0)
        button.frame = CGRect(x: CGFloat(self.frame.size.width - 25), y: CGFloat(5), width: CGFloat(25), height: CGFloat(25))
        button.addTarget(self, action: #selector(self.togglePasswordView), for: .touchUpInside)
        self.rightView = button
        self.rightViewMode = .always
    }
    @IBAction func togglePasswordView(_ sender: Any) {
        self.isSecureTextEntry = !self.isSecureTextEntry
        setPasswordToggleImage(sender as! UIButton)
    }
    }
    
  3. UITextView出口上的附加电话信息

     override func viewDidLoad() {
                 super.viewDidLoad()
                 txtPassword.enablePasswordToggle()
                 txtConfirmPassword.enablePasswordToggle()
             }
    

答案 7 :(得分:4)

Swift 3

//    MARK: Btn EyeAction
@IBAction func btnEyeAction(_ sender: Any) {

    if(iconClick == true) {
        txtPassword.isSecureTextEntry = false
        iconClick = false
    } else {
        txtPassword.isSecureTextEntry = true
        iconClick = true
    }
}

答案 8 :(得分:2)

Swift 3

passwordTF.isSecureTextEntry = true
passwordTF.isSecureTextEntry = false

答案 9 :(得分:1)

如果您需要在多个地方使用具有类似功能的TextField,则最好像下面的示例一样继承UITextField的子类-

import UIKit

class UIShowHideTextField: UITextField {

    let rightButton  = UIButton(type: .custom)

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    required override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    func commonInit() {
        rightButton.setImage(UIImage(named: "password_show") , for: .normal)
        rightButton.addTarget(self, action: #selector(toggleShowHide), for: .touchUpInside)
        rightButton.frame = CGRect(x:0, y:0, width:30, height:30)

        rightViewMode = .always
        rightView = rightButton
        isSecureTextEntry = true
    }

    @objc
    func toggleShowHide(button: UIButton) {
        toggle()
    }

    func toggle() {
        isSecureTextEntry = !isSecureTextEntry
        if isSecureTextEntry {
            rightButton.setImage(UIImage(named: "password_show") , for: .normal)
        } else {
            rightButton.setImage(UIImage(named: "password_hide") , for: .normal)
        }
    }

}

之后,您可以在任何ViewController中使用它,

class ViewController: UIViewController {

    @IBOutlet var textField: UIShowHideTextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        textField.becomeFirstResponder()
    }

}

答案 10 :(得分:1)

在Swift 4中

 var iconClick : Bool!

    override func viewDidLoad() {
        super.viewDidLoad()
        iconClick = true
     }


    @IBAction func showHideAction(_ sender: Any)
    {
        let userPassword = userPasswordTextFiled.text!;

        if(iconClick == true) {
            userPasswordTextFiled.isSecureTextEntry = false
            iconClick = false
        } else {
            userPasswordTextFiled.isSecureTextEntry = true
            iconClick = true
        }

}

答案 11 :(得分:1)

这是你的答案,不需要采取任何bool var:

@IBAction func showHideAction(sender: AnyObject) {

        if tfPassword.secureTextEntry{
            tfPassword.secureTextEntry = false

        }else{
            tfPassword.secureTextEntry = true;
        } 
    }

答案 12 :(得分:1)

正如其他人所说,该属性为secureTextEntry,但您无法在UITextField文档中找到此属性,因为它实际上是由UITextField通过{继承的{1}}协议 - https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextInputTraits_Protocol/#//apple_ref/occ/intfp/UITextInputTraits/secureTextEntry

每次按下按钮时,您都可以简单地切换此值:

UITextInputTraits

答案 13 :(得分:0)

希望这是一个比全局创建BOOL对象更简单的解决方案。

@IBAction func passwordToggleButton(sender: UIButton) {
    let isSecureTextEntry = passwordTextField.isSecureTextEntry
    passwordTextField.isSecureTextEntry = isSecureTextEntry ? false : true
    if isSecureTextEntry {
        visibilityButton.setImage(UIImage(named: "visibility"), for: .normal)
    } else {
        visibilityButton.setImage(UIImage(named: "visibility_off"), for: .normal)
    }
}

答案 14 :(得分:0)

仅将此行添加到您的代码中,将TextField名称替换为“ textfield”完​​成: 您需要更改isSecureTextEntry属性以将密码类型textFiled更改为true,如......

textField.isSecureTextEntry = true

答案 15 :(得分:0)

最短!

我认为这是用于安全输入以及更新按钮图片的最短解决方案。

@IBAction func toggleSecureEntry(_ sender: UIButton) {
    sender.isSelected = !sender.isSelected
    textfieldPassword.isSecureTextEntry = !sender.isSelected
}

根据选择的状态(默认为/ default)分配按钮的显示/隐藏图片,无需创建任何变量或插座。

答案 16 :(得分:0)

 sender.isSelected = !sender.isSelected
    if(sender.isSelected == true) {
        RegPasswordField.isSecureTextEntry = false
        sender.setBackgroundImage(UIImage(systemName: "eye.fill"), for: .normal)
            } else {
                RegPasswordField.isSecureTextEntry = true
                sender.setBackgroundImage(UIImage(systemName: "eye"), for: .normal)
            }

答案 17 :(得分:0)

这在 Swift 5.0 上对我有用

@IBAction func changePasswordVisibility(_ sender: UIButton) {
    passwordField.isSecureTextEntry.toggle()
    if passwordField.isSecureTextEntry {
        if let image = UIImage(systemName: "eye.fill") {
            sender.setImage(image, for: .normal)
        }
    } else {
        if let image = UIImage(systemName: "eye.slash.fill") {
            sender.setImage(image, for: .normal)
        }
    }
}

按钮属性:

enter image description here

结果:

enter image description here enter image description here

答案 18 :(得分:0)

对于Xamarin人员:

passwordField.SecureTextEntry = passwordField.SecureTextEntry? passwordField.SecureTextEntry = false:passwordField.SecureTextEntry = true;

答案 19 :(得分:0)

@objc func togglePasscode(){

switch textfield.isSecureTextEntry{
      case true:  textfield.isSecureTextEntry = false 
      case false: textfield.isSecureTextEntry = tree 
}
}

这是使用Switch语句的简单易读的解决方案。

答案 20 :(得分:0)

在swift 4中尝试此代码,尝试在控制器中创建可重用的代码。我在故事板中为按钮设置了不同的图像,如链接https://stackoverflow.com/a/47669422/8334818

所示
@IBAction func clickedShowPassword(_ sender: UIButton) {
        var textField :UITextField? = nil
        print("btn ",sender.isSelected.description)
        switch sender {
        case encryptOldPswdBtn:
            encryptOldPswdBtn.isSelected = !encryptOldPswdBtn.isSelected
            textField = oldPasswordTextField

        default:
          break
        }

        print("text ",textField?.isSecureTextEntry.description)
        textField?.isSecureTextEntry = !(textField?.isSecureTextEntry ?? false)

    }

答案 21 :(得分:0)

试试这一行:

@IBAction func btnClick(sender: AnyObject) {
    let btn : UIButton = sender as! UIButton
    if btn.tag == 0{
        btn.tag = 1
        textFieldSecure.secureTextEntry = NO
    }
    else{
        btn.tag = 0
        textFieldSecure.secureTextEntry = NO;
    }
}

答案 22 :(得分:0)

首先你需要为不同的状态(选择或正常)设置眼睛按钮的图像(可见或隐藏)

连接IBAction并编写像

这样的代码
@IBAction func btnPasswordVisiblityClicked(_ sender: Any) {
        (sender as! UIButton).isSelected = !(sender as! UIButton).isSelected
        if (sender as! UIButton).isSelected {
            txtfPassword.isSecureTextEntry = false
        } else {
            txtfPassword.isSecureTextEntry = true
        }
    }

this is example of "How to set image for different state of button"

答案 23 :(得分:0)

分配值从YES/NO更改为true/false布尔值。

password.secureTextEntry = true //Visible
password.secureTextEntry = false //InVisible

你可以尝试这个代码.. 我认为这很有帮助。

答案 24 :(得分:0)

@IBAction func eye_toggle_clicked(sender: AnyObject)
{
    if toggleBtn.tag == 0
    {
        passwordTxt.secureTextEntry=true
        toggleBtn.tag=1
    }
    else
    {
        passwordTxt.secureTextEntry=false
        toggleBtn.tag=0
    }
}

答案 25 :(得分:0)

使用带眼睛图像的按钮
并使buttonHandler方法
为值为1的按钮设置标记

-(IBAction) buttonHandlerSecureText:(UIButton *)sender{
      if(sender.tag ==1){
            [self.textField setSecureTextEntry:NO];
            sender.tag = 2;
      }
      else{
            [self.textField setSecureTextEntry:YES];
            sender.tag = 1;
      }
}