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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37873119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:25:57  来源:igfitidea点击:

How to toggle a UITextField secure text entry (hide password) in Swift?

iosswiftuitextfield

提问by SwiftyJD

I currently have a UITextfieldwith an eye icon in it that when pressed is supposed to toggle the secure text entry on and off.

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

secure text entry

安全文本输入

I know you can check mark the "secure text entry" box in the attributes inspector but how to do it so it toggles whenever the icon is pressed?

我知道您可以在属性检查器中勾选“安全文本输入”框,但如何做到这一点,以便在按下图标时切换?

回答by Iyyappan Ravi

Use this code,

使用此代码,

iconClick is bool variable, or you need other condition check it,

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

var iconClick = true

eye Action method:

眼睛动作方法:

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

        iconClick = !iconClick
    }

hope its helpful

希望它有帮助

回答by zath

An unintended side-effect of this is that if the user toggles to insecure, and then backto secure, the existing text will be cleared if the user continues typing. The cursor may also end up in the wrong position unless we reset the selected text range.

一个意想不到的副作用是,如果用户切换到不安全状态,然后切换安全状态,如果用户继续输入,现有文本将被清除。除非我们重置选定的文本范围,否则光标也可能会出现在错误的位置。

Below is an implementation that handles these cases (Swift 4)

下面是处理这些情况的实现(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
        }
    }
}

This snippet is using the replace(_:withText:)function because it triggers the .editingChangedevent, which happens to be useful in my application. Just setting text = existingTextshould be fine as well.

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

回答by Suryakant Sharma

Why to use an extra var. In the action method of the eyebutton just do as below

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

password.secureTextEntry = !password.secureTextEntry

UPDATE

更新

Swift 4.2(as per @ROC comment)

Swift 4.2(根据@ROC 评论)

password.isSecureTextEntry.toggle()

回答by Eugene Chybisov

Swift 4solution

斯威夫特 4解决方案

You don't need extra if statement for simple toggle isSecureTextEntry property

对于简单的切换 isSecureTextEntry 属性,您不需要额外的 if 语句

func togglePasswordVisibility() {
        password.isSecureTextEntry = !password.isSecureTextEntry
    }

But there is a problem when you toggle isSecureTextEntry UITextField doesn't recalculate text width and we have extra space to the right of the text. To avoid this you should replace text this way

但是当您切换 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!)
        }
    }

UPDATE

更新

Swift 4.2

斯威夫特 4.2

Instead of

代替

password.isSecureTextEntry = !password.isSecureTextEntry

you can do this

你可以这样做

password.isSecureTextEntry.toggle()

回答by Phani Sai

Use UITextFiled rightView to show toggle button

使用 UITextFiled rightView 显示切换按钮

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

回答by Mad Burea

For Objective c

对于目标 c

set image for RightButton In viewdidload Method

在 viewdidload 方法中为 RightButton 设置图像

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

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

and then set action method for that RightButton

然后为该 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];
        }

    }
}

回答by Bishal Ghimire

If you need TextField with similar feature in multiple places its best to subclass the UITextFieldlike follwing example -

如果您需要在多个地方具有类似功能的 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)
        }
    }

}

After which you can use it in any ViewController,

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

class ViewController: UIViewController {

    @IBOutlet var textField: UIShowHideTextField!

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

}

回答by Basir Alam

Swift 3

斯威夫特 3

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

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

回答by Christopher Larsen

Swift 3

斯威夫特 3

passwordTF.isSecureTextEntry = true
passwordTF.isSecureTextEntry = false

回答by singh.jitendra

First you need to set image(visible or hide) of button of eye for different state (selected or normal)

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

than connect IBAction and write code like

比连接 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"

这是“如何为按钮的不同状态设置图像”的示例